### Polymorphic Addition Function in Crystal Source: https://www.crystal-lang.org/reference/1.14/index An example of a simple function in Crystal that performs addition. This function demonstrates Crystal's type system by showing it can handle addition for both integers and strings, returning the correct result based on the input types. This highlights the language's flexibility. ```crystal def add(a, b) a + b end add 1, 2 # => 3 add "foo", "bar" # => "foobar" ``` -------------------------------- ### Fetching and Parsing JSON API Data in Crystal Source: https://www.crystal-lang.org/reference/1.14/index This Crystal code snippet demonstrates how to make an HTTP GET request to a JSON API, parse the response, and extract specific data. It uses the 'http/client' and 'json' libraries to fetch version information from the Crystal API. This is useful for integrating with external services. ```crystal require "http/client" require "json" response = HTTP::Client.get("https://crystal-lang.org/api/versions.json") json = JSON.parse(response.body) version = json["versions"].as_a.find! { |entry| entry["released"]? != false }["name"] puts "Latest Crystal version: #{version || "Unknown"}" ``` -------------------------------- ### Flow Typing Example in Crystal Source: https://www.crystal-lang.org/reference/1.14/index This Crystal code illustrates flow typing, where the compiler tracks variable types within conditional blocks. It reads user input, checks for different conditions (nil, empty string), and safely uses string methods like 'upcase' only when the type is guaranteed to be String. This prevents runtime errors. ```crystal loop do case message = gets # type is `String | Nil` when Nil break when "" puts "Please enter a message" else # In this branch, `message` cannot be `Nil` so we can safely call `String#upcase` puts message.upcase end end ``` -------------------------------- ### Macro for Upcase Getter in Crystal Source: https://www.crystal-lang.org/reference/1.14/index An example of Crystal's macro system for metaprogramming. This macro `upcase_getter` generates a getter method for a given instance variable that returns its value in uppercase. It's used within a class to automatically create the `name` getter, demonstrating compile-time code generation. ```crystal macro upcase_getter(name) def {{ name.id }} @{{ name.id }}.upcase end end class Person upcase_getter name def initialize(@name : String) end end person = Person.new "John" person.name # => "JOHN" ``` -------------------------------- ### Basic HTTP Server in Crystal Source: https://www.crystal-lang.org/reference/1.14/index A simple Crystal program that sets up an HTTP server to listen on port 8080. It responds to requests by printing a 'Hello world' message along with the requested path. This demonstrates basic HTTP handling in Crystal. ```crystal # A very basic HTTP server require "http/server" server = HTTP::Server.new do |context| context.response.content_type = "text/plain" context.response.print "Hello world, got #{context.request.path}!" end address = server.bind_tcp(8080) puts "Listening on http://#{address}" # This call blocks until the process is terminated server.listen ``` -------------------------------- ### C Bindings for Math Library in Crystal Source: https://www.crystal-lang.org/reference/1.14/index This Crystal code shows how to create bindings to C libraries, specifically using the 'm' library for the 'pow' function. It defines the C function signature using an `@[Link]` annotation and then calls the C function as if it were a native Crystal method. This allows seamless integration with existing C code. ```crystal # Define the lib bindings and link info: @[Link("m")] lib LibM fun pow(x : LibC::Double, y : LibC::Double) : LibC::Double end # Call a C function like a Crystal method: puts LibM.pow(2.0, 4.0) # => 16.0 ``` -------------------------------- ### Concurrent Fiber Communication in Crystal Source: https://www.crystal-lang.org/reference/1.14/index Demonstrates Crystal's concurrency model using fibers and channels. Multiple fibers are spawned to send integers to a shared channel, and the main thread receives these integers. This showcases a lock-free communication pattern inspired by CSP, avoiding shared memory issues. ```crystal channel = Channel(Int32).new 3.times do |i| spawn do 3.times do |j| sleep rand(100).milliseconds # add non-determinism for fun channel.send 10 * (i + 1) + j end end end 9.times do puts channel.receive end ``` -------------------------------- ### Crystal Project Dependencies (shard.yml) Source: https://www.crystal-lang.org/reference/1.14/index This is a configuration file (`shard.yml`) for Crystal's dependency manager, Shards. It defines the project's name, version, license, authors, and lists external dependencies like 'mysql' with their source locations (GitHub) and version constraints. This file is crucial for managing project packages. ```yaml name: hello-world version: 1.0.0 license: Apache-2.0 authors: - Crys dependencies: mysql: github: crystal-lang/crystal-mysql version: ~>0.16.0 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.