#typechecking
Explore tagged Tumblr posts
mourning-again-in-america · 2 years ago
Text
checked errors expressed via sum-types is so good, especially if there's some species of inheritance for easy sum-type composition. I don't have to know what the hell any of the names mean but my coworkers can assign personal meaning to them, if I want to know what behavior triggers it I can just. yanno. ripgrep for throw @Error {whatever structured logging needs}
0 notes
notarealwelder · 6 months ago
Text
I mean it's not really (float, float) → float, is it?
It's something like...
forall a. (HasLAdd a, HasRAdd a, HasMul a, HasPow a, HasSub a) => a -> a -> a
Tumblr media
501 notes · View notes
machine-saint · 8 months ago
Text
i think my most Toxic Trait as a developer is that I get really mad at people who seem to view typechecker and similar things as obstacles to be worked around and who just generally don't give a shit about writing high quality code. I try not to let it show in professional conversations but Christ almighty
32 notes · View notes
lackhand · 4 months ago
Text
pipe operator in js
Rescuing from my drafts ca march 2023. This is no longer actually true; my company folded last year and I'm back on my gamedev non-sense (bittersweetly!). More details on that soon.
Long time no post. I'm working in elixir these days; I couldn't sleep and so was catching up on modern JavaScript; I watched nerds snipe in the gutters.
what is pipeline?
You read this; you're adjacent to >=1 programmer. It's bash piping, the output from one function goes to the next.
There's a few ways to spell it, from the explicit:
const $0 = foo(input); const $1 = bar($0); const output = baz($1);
Explicit! Legible!
Cumbersome! Weave-y!
To the Hack-style syntax, where the pipe operator creates a variable within its right hand side's scope (sort of like this:
const output = input |> foo($) |> bar($)
Just sugar on top of the above (+ variable lifetime scopes, whatever)
Nobody can agree on the magical "previous expression result" symbol
when the pipe is a series of 1 arg f()s, the ($) extra characters are gross.
To the F#-style syntax, where the calls have to be arity-1 functions:
const output = input \|> foo \|> bar
Handles the happy path 1-arg f() beautifully
requires lambdas or currying and more care for every other case.
F# wins, right?
The community seems to think so.
But it has wrinkles; every method has to be 1-arg, and the hidden closures to enable that have performance impact.
My modest proposal
I wrote this because I didn't want to post on a six-year-and-counting language proposal, but I also had an idle fancy.
To me, the problem isn't a lack of a pipe operator or other functional support.
It's @#_-+&!ing left-hand assignment and community conventions.
You can even see it in the examples, where we have const foo, a bunch of really relevant details, and then wham, we're back to the start for the next line.
What we need is:
A right-hand assignment operator, so that after calculating a variable you can stick it somewhere. Without further thought, I propose =: but I'm sure there could be improvement.
=: assigns to the RHS, and to the special variable it. By default, assigns to _ (discards) -- in addition to it.
A new keyword & local variable "it". "It" is sort of like "this", with special rules about its meaning scoped to the function in which it appears. Typechecking must respect its most recent assignment (how high of a lift is this?!). Lambdas have their own standalone it (so you need to
A community that accepts using non-descriptive variable names & scoped type checkers for this purpose -- for instance, special syntax around right-assigning to $ such that it's type checkable, variable scoped, etc.
The semicolon "operator".
Then a pipe could be written:
input =:; foo(it) =:; bar(it) =: output
Potentially with parens in certain callsites, simplifying it a bit maybe, etc.
Things to improve:
It doesn't look like a pipe.
But is that so bad, when it makes the whole thing so beautifully explicit?
It breaks LHS/RHS naming and conventions (you're assigning?! To the right hand side??!). Doesn't delete foo[bar] do the same? This seems like a very core, very forgivable case to make the code match the language. I do not usually say "x takes the value seven"; I very often do say "store 7 as 'x'".
Real downsides: so many syntax highlighters, code awareness tools etc would need to understand polymorphic horrible "it". Combined with exceptions, the values of it in a catch clause feel pretty scary.
Still, food for thought.
2 notes · View notes
theskiesareopen · 8 months ago
Text
In the past couple days we successfully got our new language to host a hello world webserver and open a hello world desktop gui, and pushed past 2ksloc of some nontrivial bootstrapping, prelude, and tests being maintained. There's still a lot to do, like implement all the missing features to make non-hello-world projects, and the typechecker is held together with duct tape and bailing wire and it really shows sometimes. Volunteers welcome if you want to suffer with me on a really cool project to push the boundaries on what's possible in a practical programming language and proof assistant.
6 notes · View notes
robustcornhusk · 1 year ago
Text
the landlord's email name is approximately Yeehaw Dan, so that's what we're calling him
apartment which i toured back on the 24th has finally gotten back to slaw... asking for her references???
3 notes · View notes
notarealwelder · 2 years ago
Text
Observations from finally getting through intro cubical type theory:
- _=_ is not primitive. refl is not primitive. How do you live like this.
- Consequently, no path induction*. How do we prove anything without that, you may ask; normally we use it for everything from composition/transitivity and symmetry to associativity and units. Well, you see:
- Path composition is primitive. You draw a box without a lid, you give paths along all sides except the lid that agree with each other on shared edges, you get the lid for free as a primop.
-- There's not an explanation of why as such. There's an explanation of how, exactly, this works in the underlying symbolic framework. Interval variables, face formulas, lattice morphisms and congruences, segmentally-defined term systems, and finicky substitution propagation rules. I wish I was kidding.
-- Except, really, 'you get the lid for free' is approximately all we need to understand. I think. So perhaps the cube-based explanations are good enough? (Well, no. They could've mentioned the formulas and systems and how exactly we're using the underlying judgment of compositions. Ah well.)
- Oh btw the most natural composition is trinary, p . q . r : w ~> x ~> y ~> z. A square without a lid has three edges to fill, see. Thankfully it did not catch on.
- How do we get everything beside compositions, right, you're probably wondering. The cheeky answer is: we're too clever with compositions, and everything is a composition if we're clever enough. (I mean, it's true, but not explanatory.)
- The real answer is CUBES. CUBES EVERYWHERE. You want refl to be a right unit? You draw a square with p on the bottom, p.refl on top, and refls on sides, and it's a lid of a certain cube. (You provide the cube also.) You want associativity of composition? Same square, (p.q).r on top, p.(q.r) on bottom, clever cube underneath. You want to contract composition of a path with its inverse into refl? You draw a square, and--you get the idea.
- You want to invert the path, and--ok, fine, that's not a cube. Path is a function, and you can flip its argument primitively, and that exchanges the endpoints, so you get a path from B to A instead. (And doing it twice gets back the original path, definitionally, no cubes required! Something is right with the world.)
---
- There's function extensionality out of the box!! We just.... fun-ext p i x = p x i and it....works.
-- (Why? On one hand, what a silly question: it typechecks, therefore....On the other, it says something important, perhaps profound about ~worlds that ordinary DTT and CuTT can inhabit. Do we have a ~weaker notion of equality in CuTT, so there're more guaranteed equalities? A different notion of function, s.t. there're fewer of them to be distinct from each other? Something less comprehensible? Probably there's an answer if you understand categorical models of either, which I don't really.)
- We want subst, we can have subst. From nonparametric transport, which derives from weird path-parametric transp, which derives from, you guessed it, a weirdly-shaped composition.
- We want properties of subst — e.g. that subst over a composition is the same as two consequent substs over components — we have our work cut out for us. No familiar idioms, no* J, reductions are weird...Basically, time to learn how to generate proofs within the theory from scratch, with little to no transfer from ordinary deptypes. Joy.
(* not true, I think; probably J is derivable. It's..unidiomatic though, and certainly not the root from which so much grows.)
16 notes · View notes
ceausescue · 1 year ago
Text
ok so what i could do is put the generation in the low bits and the lowtag (i guess narrowtag) in the high bits. but then id have like 8 bits to play with and that just seems wasteful, plus the typechecking logic would be a little annoying. hmmmm
2 notes · View notes
transienturl · 1 year ago
Text
Tumblr media
Tip: Cloudflare Workers don't save logs, so you can only access them in real time... unless you make a Discord webhook out of a muted channel in your personal server and send them over there!
Edit: Oh, and I had to switch to "types": ["@cloudflare/workers-types/experimental"] in tsconfig.json to get this to typecheck. A regular fetch seemed to work fine too, but navigator.sendBeacon seemed more semantic.
2 notes · View notes
this-week-in-rust · 1 year ago
Text
This Week in Rust 531
Hello and welcome to another issue of This Week in Rust! Rust is a programming language empowering everyone to build reliable and efficient software. This is a weekly summary of its progress and community. Want something mentioned? Tag us at @ThisWeekInRust on Twitter or @ThisWeekinRust on mastodon.social, or send us a pull request. Want to get involved? We love contributions.
This Week in Rust is openly developed on GitHub and archives can be viewed at this-week-in-rust.org. If you find any errors in this week's issue, please submit a PR.
Updates from Rust Community
Foundation
Q4 2023 Recap from Rebecca Rumbul
Project/Tooling Updates
Ruffle 2023 in review
Four challenges cargo-semver-checks has yet to tackle
rustc_codegen_gcc: Progress Report #29
Roadmap for the Xilem backend in 2024
rust-analyzer changelog #217
pq-sys 0.5.0
What's new in SeaORM 0.12.x
Rust on Espressif chips - January 24 2024
Observations/Thoughts
Making Rust binaries smaller by default
My Best and Worst Deadlock in Rust
Why SQL hang for exactly 940s? TCP and Async Rust!
Making Async Rust Reliable
Identifying Rust’s collect::() memory leak footgun
[video] embassy is now on crates.io
[video] Rust full stack web frameworks have a bright future
[video] Rust Halifax - Rust & Tell #1
[video] Why Rust will keep growing in 2024
Rust Walkthroughs
Using mem::take to reduce heap allocations
Writing your own Rust linter
Using Serde in Rust
Parsing JSON in Rust
Billion-row challenge: Rust walkthrough
Embassy on ESP: Timers
Supporting LoRa on the SparkFun expLoRaBLE Thing Plus with Rust
How to work with !Sized types in Rust
Rocket - logging in the web application
Rocket - access custom configuration in the routes
Testing with tempfiles and environment variables
Research
Profiling Programming Language Learning
Rust-lancet: Automated Ownership-Rule-Violation Fixing with Behavior Preservation
Crate of the Week
This week's crate is apistos, an OpenAPI documentation tool.
Thanks to Romain Lebran for the self-suggestion!
Please submit your suggestions and votes for next week!
Call for Participation; projects and speakers
CFP - Projects
Always wanted to contribute to open-source projects but did not know where to start? Every week we highlight some tasks from the Rust community for you to pick and get started!
Some of these tasks may also have mentors available, visit the task page for more information.
* Ockam - Have a single SqlxDatabase instance per process * Ockam - Improve database migrations to pair sql and rust migration code * Ockam - Make install.sh not fail during upgrade process * Hyperswitch - [FEATURE]: Make cache configuration configurable at runtime * Hyperswitch - [FEATURE]: Implement Code cov for local system using makefile * Hyperswitch - [FEATURE]: Setup code coverage for local tests & CI * Hyperswitch - [FEATURE]: Add domain type for client secret * Hyperswitch - [FEATURE]: Have get_required_value to use ValidationError in OptionExt
If you are a Rust project owner and are looking for contributors, please submit tasks here.
CFP - Speakers
Are you a new or experienced speaker looking for a place to share something cool? This section highlights events that are being planned and are accepting submissions to join their event as a speaker.
If you are an event organizer hoping to expand the reach of your event, please submit a link to the submission website through a PR to TWiR.
Updates from the Rust Project
453 pull requests were merged in the last week
HashMap/HashSet: forward fold implementations of iterators
dead_code treats #[repr(transparent)] the same as #[repr(C)]
fix(rust-analyzer): use new pkgid spec to compare
large_assignments: Lint on specific large args passed to functions
maybe_lint_impl_trait: separate is_downgradable from is_object_safe
never_patterns: Count ! bindings as diverging
never_patterns: typecheck never patterns
pat_analysis: Don't rely on contiguous VariantIds outside of rustc
pattern_analysis: Remove Ty: Copy bound
proc_macro: Add Literal::c_string constructor
single_use_lifetimes: Don't suggest deleting lifetimes with bounds
add #[track_caller] to the "From implies Into" impl
add Ipv6Addr::is_ipv4_mapped
add PatKind::Err to AST/HIR
add help message for exclusive_range_pattern error
add private NonZero<T> type alias
add way to express that no values are expected with check-cfg
added NonZeroXxx::from_mut(_unchecked)?
allow any const expression blocks in thread_local!
always use RevealAll for const eval queries
avoid ICEs in trait names without dyn
consolidate logic around resolving built-in coroutine trait impls
deny braced macro invocations in let-else
detect NulInCStr error earlier
improve let_underscore_lock
improved collapse_debuginfo attribute, added command-line flag
make unsafe_op_in_unsafe_fn migrated in edition 2024
restrict access to the private field of newtype indexes
simplify closure_env_ty and closure_env_param
suggest .swap() when encountering conflicting borrows from mem::swap on a slice
undeprecate lint unstable_features and make use of it in the compiler
make MIR pass name a compile-time constant
make stable_mir::with_tables sound
SMIR: make the remaining "private" fields actually private
use an interpreter in MIR jump threading
use implied bounds compat mode in MIR borrowck
validate AggregateKind types in MIR
sandwich MIR optimizations between DSE
cache local DefId-keyed queries without hashing
pack u128 in the compiler to mitigate new alignment
use UnhashMap for a few more maps
fold arithmetic identities in GVN
optimize large array creation in const-eval
implement iterator specialization traits on more adapters
optimize EscapeAscii's Display and CStr's Debug
stabilise bound_map
stabilize round_ties_even
stabilize slice_first_last_chunk
stabilize single-field offset_of!
implement strict integer operations that panic on overflow
core: introduce split_at{,_mut}_checked
un-hide iter::repeat_n
fix deallocation with wrong allocator in (A)Rc::from_box_in
use bool instead of PartialOrd as return value of the comparison closure in {slice,Iterator}::is_sorted_by
regex: make Input::new guard against incorrect AsRef implementations
cargo-rustdoc: use same path by output format logic everywhere
cargo: use pkgid spec in in JSON messages
cargo: remap common prefix only
cargo doc: add a heading to highlight "How to find features enabled on dependencies"
cargo: inherit jobserver from env for all kinds of runner
cargo: fix precise-prerelease tracking link
cargo: go back to passing an empty values() when no features are declared
cargo: improve GitHub Actions CI config
rustdoc: Allows links in headings
rustdoc: hide modals when resizing the sidebar
rustfmt: check that a token can begin a nonterminal kind before parsing it as a macro arg
rustfmt: add config option generated_marker_line_search_limit
clippy: blocks_in_conditions: do not warn if condition comes from macro
clippy: default_numeric_fallback: improve const context detection
clippy: no_effect_underscore_binding: _ prefixed variables can be used
clippy: unused_io_amount captures Ok(_)s
clippy: add suspicious_open_options lint
clippy: correctly handle type relative in trait_duplication_in_bounds lint
clippy: don't emit derive_partial_eq_without_eq lint if the type has the non_exhaustive attribute
clippy: find function path references early in the same lint pass
clippy: fix FP on semicolon_if_nothing_returned
clippy: fix multiple_crate_versions to correctly normalize package names to avoid missing the local one
clippy: fix warning span for no_effect_underscore_binding
clippy: respect #[allow] attributes in single_call_fn lint
clippy: improve wording and fix dead link in description of arc_with_non_send_sync lint
rust-analyzer: add "One" import granularity
rust-analyzer: add a new config to allow renaming of non-local defs
rust-analyzer: goto type actions for notable trait hovers
rust-analyzer: show additional value information when hovering over literals
rust-analyzer: show notable implemented traits on hover
rust-analyzer: add error recovery for use_tree_list parsing
rust-analyzer: fix panic when extracting struct from enum variant
rust-analyzer: fix progress reporting getting stuck
rust-analyzer: handle SelfParam better in "Inline call"
rust-analyzer: include for construct in convert to guarded return conditions
rust-analyzer: infer OUT_DIR when workspace root contains a symlink
rust-analyzer: make value_ty query fallible
rust-analyzer: parse macro_rules as macro name
Rust Compiler Performance Triage
This week saw a bunch of regressions caused by correctness fixes and in general doing more work in the compiler. These were offset by many improvements (especially around hashing in the compiler) that improved performance by ~2% across a large number of benchmarks. Don't get too excited about the large 45+% wins though, these were only for tiny benchmarks like helloworld. They were caused by a change in Cargo which introduces stripping of debug symbols from Rust release binaries by default, and in turn also improves compilation time for small crates.
Triage done by @kobzol. Revision range: f9c2421a..d6b151fc
Summary:
(instructions:u) mean range count Regressions ❌ (primary) 0.7% [0.2%, 1.5%] 11 Regressions ❌ (secondary) 2.2% [0.2%, 9.9%] 26 Improvements ✅ (primary) -3.2% [-47.5%, -0.2%] 191 Improvements ✅ (secondary) -7.9% [-46.5%, -0.1%] 123 All ❌✅ (primary) -3.0% [-47.5%, 1.5%] 202
4 Regressions, 4 Improvements, 9 Mixed; 4 of them in rollups 48 artifact comparisons made in total
Full report here
Approved RFCs
Changes to Rust follow the Rust RFC (request for comments) process. These are the RFCs that were approved for implementation this week:
No RFCs were approved this week.
Final Comment Period
Every week, the team announces the 'final comment period' for RFCs and key PRs which are reaching a decision. Express your opinions now.
RFCs
No RFCs entered Final Comment Period this week.
Tracking Issues & PRs
[disposition: close] Add a default flag for enum documentation
[disposition: merge] impl From<&[T; N]> for Cow<[T]>
[disposition: merge] Tracking Issue for array_methods
Language Reference
No Language Reference RFCs entered Final Comment Period this week.
Unsafe Code Guidelines
No Unsafe Code Guideline RFCs entered Final Comment Period this week.
New and Updated RFCs
eRFC: Iterate on and stabilize libtest's programmatic output
Call for Testing
An important step for RFC implementation is for people to experiment with the implementation and give feedback, especially before stabilization. The following RFCs would benefit from user testing before moving forward:
No RFCs issued a call for testing this week.
If you are a feature implementer and would like your RFC to appear on the above list, add the new call-for-testing label to your RFC along with a comment providing testing instructions and/or guidance on which aspect(s) of the feature need testing.
Upcoming Events
Rusty Events between 2024-01-24 - 2024-02-21 ��
Virtual
2024-01-24 | Virtual (Berlin, DE) | WeAreDevelopers Community
WeAreDevelopers LIVE - Rust Day
2024-01-25 | Virtual (Charlottesville, NC, US) | Charlottesville Rust Meetup
Crafting Interpreters in Rust Collaboratively
2024-01-25 | Virtual (Linz, AT) | Rust Linz
Rust Meetup Linz - 36th Edition
2024-01-25 | Virtual (Mexico City, DF, MX) | Rust MX
Iniciando 2024 con Rust
2024-01-28 | Virtual (Wrocław, PL) | Stacja IT Wrocław
Wprowadzenie do języka Rust
2024-01-30 | Virtual | Bevy Game Development
Bevy Meetup #1
2024-01-30 | Virtual (Buffalo, NY, US) | Buffalo Rust User Group
Buffalo Rust User Group
2024-01-30 | Virtual (Dallas, TX, US) | Dallas Rust
Last Tuesday
2024-01-31 | Virtual (Cardiff, UK) | Rust and C++ Cardiff
Rust for Rustaceans Book Club launch!
2024-02-01 | Virtual + In Person (Barcelona, ES) | BcnRust
12th BcnRust Meetup - Stream
2024-02-01 | Virtual (Berlin, DE) | OpenTechSchool Berlin + Rust Berlin
Rust Hack n Learn | Mirror: Rust Hack n Learn
2024-02-03 | Virtual + In-person (Brussels, BE) | FOSDEM 2024
FOSDEM Conference: Rust devroom - talks
2024-02-03 | Virtual (Kampala, UG) | Rust Circle
Rust Circle Meetup
2024-02-04 | Virtual | Rust Maven
Web development with Rocket - In English
2024-02-07 | Virtual (Indianapolis, IN, US) | Indy Rust
Indy.rs - with Social Distancing
2024-02-08 | Virtual (Charlottesville, NC, US) | Charlottesville Rust Meetup
Crafting Interpreters in Rust Collaboratively
2024-02-08 | Virtual (Nürnberg, DE) | Rust Nüremberg
Rust Nürnberg online
2024-02-10 | Virtual (Wrocław, PL) | Stacja IT Wrocław
Rust – budowanie narzędzi działających w linii komend
2024-02-13 | Virtual (Dallas, TX, US) | Dallas Rust
Second Tuesday
2024-02-15 | Virtual (Berlin, DE) | OpenTechSchool Berlin + Rust Berlin
Rust Hack n Learn | Mirror: Rust Hack n Learn
2024-02-21 | Virtual (Vancouver, BC, CA) | Vancouver Rust
Rust Study/Hack/Hang-out
Europe
2024-01-24 | Zagreb, HR | impl Zagreb for Rust
Rust Meetup 2024/01: WebGPU intro using Rust
2024-01-25 | Augsburg, DE | Rust Meetup Augsburg
Augsburg Rust Meetup #5: Async Part2 and Async in action
2024-01-25 | Vienna, AT | Rust Vienna
Rust Vienna Meetup - January - Blockchains and Data Pipelines
2024-02-01 | Hybrid (Barcelona, ES) | BcnRust
12th BcnRust Meetup
2024-02-03 | Brussels, BE | FOSDEM '24
FOSDEM '24 Conference: Rust devroom - talks | Rust Aarhus FOSDEM Meetup
2024-02-03 | Nürnberg, BY, DE | Paessler Rust Camp 2024
Paessler Rust Camp 2024
2024-02-06 | Bremen, DE | Rust Meetup Bremen
Rust Meetup Bremen [1]
2024-02-07 | London, UK | Rust London User Group
Rust for the Web — Mainmatter x Shuttle Takeover
2024-02-08 | Bern, CH | Rust Bern
Rust Bern Meetup #1 2024 🦀
North America
2024-01-24 | Austin, TX, US | Rust ATX
Rust Lunch - Fareground
2024-01-27-28 | Calgary, AB, CA | Rust Calgary
Harnessing Rust for Real-World Problems hackathon: Day 1
Harnessing Rust for Real-World Problems hackathon: Day 2
2024-01-25 | Mountain View, CA, US | Mountain View Rust Meetup
Rust Study/Hack/Hang-out
2024-01-30 | Cambridge, MA, US | Boston Rust Meetup
Harvard Square Rust Lunch
2024-02-07 | Brookline, MA, US | Boston Rust Meetup
Coolidge Corner Brookline Rust Lunch, Feb 7
2024-02-12 | Minneapolis, MN, US | Minneapolis Rust Meetup
Minneapolis Rust: Open Source Contrib Hackathon & Happy Hour
2024-02-13 | New York, NY, US | Rust NYC
Rust NYC Monthly Mixer
2024-02-13 | Seattle, WA, US | Cap Hill Rust Coding/Hacking/Learning
Rusty Coding/Hacking/Learning Night
2024-02-15 | Boston, MA, US | Boston Rust Meetup
Back Bay Rust Lunch, Feb 15
2024-02-15 | Seattle, WA, US | Seattle Rust User Group
Seattle Rust User Group Meetup
Oceania
2024-02-06 | Perth, WA, AU | Perth Rust Meetup Group
Rust Feb 2024 Meetup
If you are running a Rust event please add it to the calendar to get it mentioned here. Please remember to add a link to the event too. Email the Rust Community Team for access.
Jobs
Please see the latest Who's Hiring thread on r/rust
Quote of the Week
The functional ML roots of the language, Graydon's first Rust compiler was written in OCaml, shine through, influencing it right from the start.
It's not "C++ but better".
It's Haskell standing on Lisp's shoulders, hiding in C's coat to sneak into PRDCTN. (The fancy nightclub where all the popular language's hang out)
– tris on his "No Boilerplate" Youtube channel
Thanks to PrototypeNM1 for the suggestion!
Please submit quotes and vote for next week!
This Week in Rust is edited by: nellshamrell, llogiq, cdmistman, ericseppanen, extrawurst, andrewpollack, U007D, kolharsam, joelmarcey, mariannegoldin, bennyvasquez.
Email list hosting is sponsored by The Rust Foundation
Discuss on r/rust
1 note · View note
anocana · 3 months ago
Text
digging down to the causes i think at least half of this was not having LSP feedback which is incredibly crucial for how i write [...] lol. if i'd been able to see whether my shit typechecked at a glance i would have spent so much less time stumbling around
had a job interview today which was going quite well through the non-technical parts and then we got to the live coding where I made one structural mistake at the beginning and completely fucked myself by spending the rest of the 20 minutes psyching myself out over it
8 notes · View notes
mourning-again-in-america · 2 years ago
Text
Very funny to me that one of the best pitches (if true) for any webshit framework is "what if webdev were good"
1 note · View note
mrbaguvix · 5 years ago
Text
Mapping PropTypes to TypeScript types
Tumblr media
The earlier React props were typed-checked by the prop-types package which looked something like this:
MyComponent.propTypes = { message: PropTypes.string, count: PropTypes.number, disabled: PropTypes.bool, level: PropTypes.symbol, }
But with typescript everything must be typed, either implicitly or explicitly.
TypeScript:
interface Props { message: string count: number disabled: boolean level: Symbol }
Then we have Function types
Prop types:
MyComponent.propTypes = { onClick: PropTypes.func, onChange: PropTypes.func, onSelect: PropTypes.func, }
TypeScript:
interface Props { onClick: () => void onChange: (val: string) => void onSelect: (id: string, val: number) => void }
Array & object types
Prop types:
MyComponent.propTypes = { style: PropTypes.shape({  color: PropTypes.string,  fontSize: PropTypes.number, }), person: PropTypes.exact({  name: PropTypes.string,  age: PropTypes.number,  employed: PropTypes.bool,  status: PropTypes.oneOf([    'single',    'dating',    'other',  ]), }), names: PropTypes.arrayOf(PropTypes.string), items: PropTypes.arrayOf(  PropTypes.shape({    title: PropTypes.string,    active: PropTypes.boolean,  }), ), }
TypeScript:
interface Props { style: {  color: string  fontSize: number } person: {  name: string  age: number  employed: boolean  status:    | 'single'    | 'dating'    | 'other' } names: string[] items: {  title: string  active: boolean }[] }
Required vs. Optional
With PropTypes, the props are all optional by default and you have to use .isRequired. While in TypeScript, all props are required by default, so you need to mark them as optional using ?
Prop Types:
MyComponent.propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, isAdmin: PropTypes.bool, }
TypeScript:
interface Props { title: string description: string isAdmin?: boolean }
Conclusion
You can see how using PropTypes relates differently with Typescript types. Interfaces take the shapes or model while types are custom data types. Typescript interfaces are easier to construct and maintain.
You can also use interfaces to extend a class.
0 notes
shae-bun · 1 year ago
Text
Saw this in a reblog.
I'm a big fan of Lua, but particularly Roblox's Luau which makes some well thought out changes to Lua 5.1, including tooling for static typechecking, bringing in essential features from newer versions, and making the fastest way to do things the idiomatic way. (for example, in Lua 5.1 the fastest way to loop through an array is a verbose numeric for loop. In Luau, the fastest way is the idiomatic way of using the built-in table iteration feature.) It's also consistently maintained and gets improvements often.
Scheduling in Lua is typically done on a single thread with coroutines. Coroutines allow a script to stop and wait for a value. What this looks like from the runtime side is:
Luau calls a function which is supposed to yield
Inside the function body, you coroutine.yield then hand the coroutines to your scheduler
The scheduler checks every frame which coroutines should be resumed. If they meet resumption criteria — like getting response values or having yielded for long enough — you coroutine.resume them.
Tying in with this, the way you run multiple scripts "at once" is you load the script to a function, then you stick that function on the scheduler for immediate resumption. Every frame multiple scripts can run in sequence up to their yielding point.
Your scheduler can be written from the C side or from the Luau side. When I wrote a scheduler I found it easier to write it on the Luau side — you just invoke the same Luau function every frame and that function handles all of the scheduler/resumption logic. I only really found that easier though because my "C side" was rust and I couldn't work out the lifetimes to make the scheduler easy to write in rust.
Anyways, I think a lot of other scripting languages with green threads work similarly. Also, most of this applies to both Lua and Luau, I just called it Luau because it's what I'm used to.
I can't decide 🎵
Okay, let's have a good think about scripting languages that I might use in Project Special K. I wrote about this before, but really I'm just trolling for comments and suggestions.
Option 1 - Lua
Relatively easy to implement, especially with something like Sol on top.
Well known, often used for game scripts.
I have no earthly clue how to handle multiple objects running their own scripts simultaneously, let alone the whole "wait for some other object to signal back" that I described before.
Option 2 - JavaScript
Could be a nice challenge to implement, maybe with something like Duktape?
Well known, but not as often used for game scripts as Lua.
The third point is exactly the same as for Lua.
Option 3 - bespoke Lisp-like
Tricky to implement, but I've done it a bunch of times now to varying degrees.
Not as well known nowadays, I suppose, compared to JS and Lua.
I already know how to allow for cooperative multi-threading and waiting for other objects to finish, as described before. Just gotta implement the whole thing.
Option 4 - Event Flow
The script engine used in Animal Crossing New Horizons, Legend of Zelda Breath of the Wild and Tears of the Kingdom, and probably many other Switch games.
This option is a joke to make the list longer.
Obviously supports waiting for outside things.
Option 5 - Something else
Who knows, maybe one of you reading this has a better idea?
As a reminder of what I kept referring to, there would be several things running simultaneously like villagers, gift balloons, bugs, the hourly weather and chime thing, the player, and the UI. When you talk to a villager, they stop what they're doing and run a script. That script can then cause a dialogue box to appear by spawning in a new game object. The script should then sit and wait until the dialogue box is dismissed, all while the villager sits and waits until the script signals it's done, while the dialogue box and script can trigger animations to play on the villager and player alike... all while all these other objects still process in the background, and may themselves run scripts.
I'd rather not start on implementing something as in-depth as a script system, let alone with a feature such as that, without being certain it's not a very bad idea.
Doesn't need to be the best idea. Just not a very bad one.
52 notes · View notes
tototavros · 5 years ago
Text
one of those nights where instead of dreams my brain just sends me long streams of "noise" and tells me it's important, figure it out
1 note · View note
otter-byte · 3 years ago
Text
Fuck everyone, I give up on this dynamically typed runtime hellscape (typescript) and I'm ascending to a higher plane (Rust), I will no longer be held hostage to the Cunk Cost Fallacky
1 note · View note