6 ms·
Functional programmers need to take a look at Zig
- dnautics 5mo agoio is not a monad. theres nothing stopping you from stashing a global io "object" and just passing the global wherever you interface with the stdlib. It's dependency injection. and yes, you can model dependecies like a monad but most people, even in less pure fp langs, don't. i don't really say this to just be a pedant, but if you're an fp enjoyer, you will be disappointed if you get the picture that zig is fp-like, outside of a few squint-and-it-looks-like things
- tux1968 5mo agoMy reading of the article, was that the author seems to be in search of a new paradigm, that moves beyond what he sees as the limitations of "fp-like" languages as they exist today. His point appears to be that Zig provides the benefits of "fp-like" languages that exist today, while avoiding at least some of the downsides. And he does admit you may have to squint, to appreciate the fp capabilities provided by Zig.
- HelloNurse 5mo agoIt is worth noting that some rather "enlightened" type system features are common in other imperative languages, not particularly novel ides in Zig. For example Swift enums, while in some ways clunky, can do a decent job both as newtypes and as sum types (unlike Java enums, which are a fixed collection of instances of the same class).
- danieltanfh95 5mo agoI am not even sure if its a general pattern (inject any dependency?) or a specific pattern they added to Zig
- dnautics 5mo agoidk in elixir we basically do exactly whats happening with io parameters when mocking or swapping implementations that all satisfy the same behaviour. here. i am not the only one that refers to it as dependency injection: https://daily.dev/blog/zig-async-io-io-uring-zig-0-16-rethinks-concurrent-programming#how-zigs-stdio-abstraction-works https://daily.dev/blog/zig-async-io-io-uring-zig-0-16-rethin... "Zig 0.16 introduces std.Io, a flexible I/O abstraction that uses dependency injection, similar to the Allocator interface"
- danieltanfh95 5mo agoSigh. I meant that the zig authors did not make it a general pattern and just slapped on the DI pattern specifically for io, instead of generalising the abstraction so people can DI stuff.
- dnautics 5mo agoit's a general pattern. Allocators use the exact sane vtable mechanism. It's not like first class or anything, but that's fine: its enough of a pain in the ass to set it up that you dont start doing BeanFactoryFactory everywhere
- immanuwell 5mo ago[dead]
- jstanley 5mo ago> Noise is anything that must be written for the program to function that is not relevant to the domain. > ... > What facilities does the language provide me to create correct-by-construction systems and how easily can I program the type-system. Isn't programming the type-system orthogonal to the program's domain in the same way that manual memory management is?
- rdevilla 5mo agoNo? I don't agree. The domain can be strongly modelled in the types; for instance, declaring kilometers, seconds, etc. instead of using primitive floats/reals everywhere, to statically prevent dimensional analysis issues.
- pyrolistical 5mo agoI don’t get it Why write: EqPoint.eql(a, c) When you can write: Point.eql(a, c)
- riffraff 5mo agoI believe EqPoint allows you to pass around a bag of functions (aka an interface, which Zig does not have as a concept) to functions which can be written in terms of "I need these functions" rather than in terms of a concrete type.
- psychoslave 5mo agoFor the same reason things like "a, c as equal points" or even "some and other as equal points". That could just as easily be automatically parsed. Just a matter of sticking conventions, as if scriptural terseness was of any utility in the kind of case, apart maybe for esoteric representation that will filter non initiated people.
- continuational 5mo agoDo you really prefer this: fn Maybe(comptime T: type) type { return union(enum) { value: T, nothing, const Self = @This(); pub fn just(the_val: T) Self { return .{ .value = the_val }; } pub fn nothing() Self { return .nothing; } } } Over this? data Maybe a = Just a | Nothing
- rdevilla 5mo agoMy old memories of Guava in Java 6 have been triggered.
- rene_d 5mo agoOptionals handle this in zig: var value: ?T = null; Write: value = 10; Read: if (value) |x| x+=1
- nesarkvechnep 5mo agoCame to say this. Early in my career I really thought implementing Maybe in any language is necessary but not I know better. Use the idioms and don’t try to make every language something it’s not.
- continuational 5mo agoSure, but this is an example from the article, and pertains to sum types in general, not just Maybe.
- deleted 5mo ago[deleted]
- dnautics 5mo agoi dont think its generally a good idea to be making complex type generators like this in zig. just write the type out. the annoyingness of the thing you tried to do in zig is a feature. its a "don't do this, you will confuse the reader" signal. as for optional, its a pattern that is so common that it's worth having builtin optimizations, for example @sizeOf(*T) == @sizeOf(usize) but @sizeOf(?*T) != @sizeOf(?usize). if optional were a general sum type you wouldn't be able to make these optimizations easily without extra information
- voxl 5mo agoA functional programmer who casts away proper sum types and pattern matching is no functional programmer at all
- rgoulter 5mo agoI thought lisps were all functional programming, and lack sum types and pattern matching? In which case, what's the term for the "proper sum types and pattern matching" flavour of things?
- rienbdj 5mo ago(Pure) expression orientation is the true marker of FP
- shirogane86x 5mo agoI think the lisp situation is peculiar, for 3 main reasons: - most of them are dynamically typed (thus don't need sum types, as there are no types). The ones that do have gradual type systems likely either implement some form of them (off the top of my head I can only remember typed racket, and I think it implements them through union types) - not all lisps lean functional: I believe that's mostly a prerogative of scheme and clojure (and their descendants); something like CL is a lot more procedural, iirc - in most lisps, thanks to macros, you probably don't need the language to support some sort of match construct out of the box: just implement it as a macro [1] In general the "proper sum types" side of functional programming is just the statically typed one, but even in dynamically typed FP languages you end up adopting sum type-esque patterns, like elixir's error handling (which closely resembles the usual Either/Result type, just built out of tuples and atoms rather than a predefined type), and I assume many lisps adopt similar patterns as well [1] https://github.com/clojure/core.match https://github.com/clojure/core.match
- iLemming 5mo ago> most of them are dynamically typed (thus don't need sum types, as there are no types) I think you're conflating. "No compile type checking" and "no sum types" are different things. Sum types are about modeling data as "one of these variants". You can do that in any language - the difference is whether the compiler enforces exhaustive handling or not. Clojure (for example) absolutely has the equivalent of sum types, just expressed idiomatically rather than enforced by a compiler - multimethods, keywors as tags or tuple vectors can be used as represenation of tagged unions. Malli and Spec both provide sum types with validation (it just happens runtime).
- givemeethekeys 5mo agoIsn't the whole point of abstraction to not care about whats underneath unless you really have to? But ideally, you don't because the abstraction is "good enough"? I haven't heard anyone writing code in Elixir complain about performance issues.
- nesarkvechnep 5mo agoWhat’s up with the last paragraph? Nobody is complaining because the BEAM is good enough for the typical use case?
- dnautics 5mo agobecause you're not reaching for elixir when you need performance. btw we do sometimes bitch about performance :)
- nesarkvechnep 5mo agoI asked because I do it sometimes too.
- abrookewood 5mo agoBut then we have ports/NIFs etc that shell out to Rust & Zig ...
- nesarkvechnep 5mo agoNot a silver bullet. There are also C nodes but they’re used even less.
- dnautics 5mo ago> NIFs that shell to zig I'm aware
- givemeethekeys 5mo agoI meant to point out that, for the use-cases where functional languages are used - production performance seems very acceptable, compared to having to micromanage memory allocation.
- NordStreamYacht 5mo agoI'm still fighting with Elixir and losing - for some reason I can't get my head around all the slightly different ways to initialise stuff.
- dnautics 5mo ago"slightly different ways to initialise stuff." can you elaborate? theres only what 11 datatypes in elixir?
- buzzerbetrayed 5mo agoPerhaps they are referring to the syntactic sugar around keyword lists? [a: 1, b: 2] == [{:a, 1}, {:b, 2}] Or maybe atom vs string keys in maps? %{a: 1} vs %{"b" => 1} Or keyword lists always needing to come last in lists? [some: :value, :another] # error [:another, some: :value] # valid Or maybe something else entirely. Those are just things I remember having to lookup repeatedly when I was first learning elixir.
- NordStreamYacht 5mo agoThese are the ones. I just can't remember them.
- dnautics 5mo agocompletely reasonable. eventually you internalize them, and the rules aren't that bad and are consistent.
- abrookewood 5mo agoDo you mean config and runtime variables etc (i.e. in Phoenix)?
- fk2026 5mo ago[dead]
- deleted 5mo ago[deleted]
- drgiggles 5mo agoIt’s possible (even true in my opinion) that garbage collected functional languages and low level languages like Zig are both great, and serve different purposes. I actually ship stuff in Haskell believe it or not. I also think Zig is very cool and have played around with it quite a bit. Yes, garbage collection hurts performance, but the reality is that the overwhelming majority of all software does not suffer from the performance loss between well written code in a reasonably performant functional gc language and a highly performant language with manual memory management. It’s just not important. But not having to deal with the cognitive overhead of managing memory and being able to deal in domain specific abstractions only is a massive win for developer productivity and code base simplicity and correctness. I think OxCamls approach of opting in to more direct control of performance is interesting. I also think it’s great that many functional patterns are making their way into imperative first languages. Language selection is always about trades offs for your specific use case. My team writes Haskell instead of Rust because Haskell is plenty fast for our use case and we don’t have to write lifetime annotations everywhere and think about borrowing. If we needed more performance we would have no choice but to explore other languages and sacrifice some developer experience and productivity, that’s very reasonable. I’m also not saying performance doesn’t matter (if you’re writing for loops in Python, stop). But this read to me like “because better performance exits with manual memory management, all garbage collectors are bad, so I’ll force zig to be something it’s not in order to gain performance I probably don’t need”. Which to me is an odd take. A more measured way of thinking about this might be, it can be useful to leverage functional patterns where appropriate in low level languages, if you find yourself needing to write code in one.
- andriy_koval 5mo ago> My team writes Haskell instead of Rust because Haskell is plenty fast for our use case and we don’t have to write lifetime annotations everywhere and think about borrowing. it happened that in rust you also don't have to write lifetime annotations everywhere. Depending on how your code is structured, compiler infers lifetime very well. In my current project we have lifetime annotations in very few places.
- faangguyindia 5mo agoThese days I just use a few languages: 1. Go, when I first saw code I wrote almost a decade ago still compiles and runs in Go, I decided to use Go for everything. There were some initial troubles when I started using it a decade ago, but now it's painless. 2. Haskell, I use it for DSL and state machines. 3. Bash for all deployment scripts and everything. 4. TypeScript, well for the frontend. Lately, I’ve been using Go and SQLite for nearly everything. I don't think I’ve any motivation to look at any other language. I gave up on Java, Python, Ruby, Rust, C++, and C# long ago. Fun fact: Same thing for cloud, I just don't use managed cloud services anymore. I only use VMs or dedicated servers. I've found when you want to run a service for decades+, you’ve got to run your own service if you want it not to cost a lot in the long run. I manage a few MongoDB, PostgreSQL clusters. Most of the apps like email lists marketer (for marketing, sending thousands of email each day) are simple Go app + SQLite using less than 512MB RAM. Same for SaaS billing, the solution is entirely written in Go and uses Postgres. (I didn’t feel safe here using SQLite for this for a multi-tenant setup.) Our chat/ticketing system is SQLite + Go. Deployment is easy, just upload Go cross-compiled binary + systemd service file, alloy picks up log and drops it graphana which has all alerts there. I don't need to worry about "speed" for anything I do in Go, unlike Ruby/Python. When something has to be correct I define it model it in Haskell as its rich type system helps you write correct code. Though setup is not painless as Go, decent performance. I write good documentation, deployment instructions right into mono repo. For a small team this is more than enough imho. No Docker, no Kubernetes, just using simple scripts + graphana + prometheus + Loki and for alloy/nodeexporter. Life couldn't be any simpler than this.
- 5d41402abc4b 5mo agoWhy did you give up on Java and Rust?
- faangguyindia 5mo agoJava is a resource hog when you use patterns and libraries popular in Java land. When you are working in the Java ecosystem, you just assume that this much resource is needed by the app! But when you'll code the same thing in Go using the same methods, you'll find resource usage is really very low. We’ve a 1: 1 copy of the app; on JVM, it's using 2GB RAM using Spring Boot, and on Go, it runs on 512MB RAM and is blazingly fast. ofc, it's possible to tune java app but why bother? when we get same low resource usage and better performance in Go from get go while still writing naive and dumb code? Deployment is super simple in Go, upload a single cross compiled binary it's done. Very simple and easy. Rust needs a lot more effort to write correct code than Go in my experience. We get the same performance out of Go, with much less effort. At some point, it's just cheaper to start one extra instance than perform some low-level optimisation; modern hardware is fast enough that Rust-level optimisation is rarely needed for what we do.
- Antibabelic 5mo ago> Well, I’ve been radicalized. I’ve learned enough performance-oriented programming to be dissatisfied with the common functional languages (Haskell, OCaml, Common Lisp/Clojure, Scheme) because each of these languages are predicated on the existence of garbage collection and heaps. I would take another look at Common Lisp if I were the author. Manual memory management is very much an option where you need it.
- lukaslalinsky 5mo agoAnyone preferring functional programming will be extremely disappointed with Zig. And I'm saying this as a big user of Zig. It's a language for imperative code. And Io is not a monad, just a bunch of virtual methods doing the actual I/O.
- crvdgc 5mo agocomptime is a restricted form of dependent typing. In addition to the normal value to value, type to type, and type to value functions, in comptime, you can write static value to type functions. In full dependent type, you can in addition write dynamic value to type functions, completing the value to type corner. So in terms of typing strength, plain Haskell < Zig < dependent type languages.
- sbt567 5mo agoI've been recently trying to port my simple program to Mojo to find out how the language looks like and feel. And the comptime feature (which inspired by Zig I think) is absolute joy to use. It helps a lot that the syntax looks like Python also. Excited to see how the language will become in the future particularly for its memory safety paradigm.
- SkiFire13 5mo ago> I see http_client as existing in a Reader monad that contains an allocator and an IO interface. This is exactly how the IO monad (and for that matter IO#) works in Haskell. The fact that the Zig people came up with this independantly speaks not just to the universal nature of monads (and the algebraic structures of programming languages) Honestly this sounds like monad bullshit. That's a struct/class/ADT/whatever you want to call it, they existed since forever. The only idea Zig had was that maybe we shouldn't make them global instances.
- arikrahman 5mo agoThis is the approach Jank is taking, which is ironic because Zig is decoupling from LLVM.
- mrkeen 5mo agoMaybe procedural programmers should take a look instead. I don't see functions. a function from a set X to a set Y assigns to each element of X exactly one element of Y. [https://en.wikipedia.org/wiki/Function_(mathematics) https://en.wikipedia.org/wiki/Function_(mathematics)]
- rienbdj 5mo agoUnder this strict definition you can’t even throw exceptions!
- mattalex 5mo agoOf course you can: you just have to define it in your type. The output set becomes a union type of the normal output and whatever you want as an exception. If you write this as a monad, your get very similar syntax to procedural code.
- rienbdj 5mo agoI get what you are saying, but… An exception is different to an Either result type. Exceptions short circuit execution and walk up the call tree to the nearest handler. They also have very different optimization in practice (eg in C++)
- mattalex 5mo agoI'm what way is that different? You return early and the call Cascades up the call chain until you handle it (otherwise it's always an "either" results) In practice you use something like an exception monad, which makes this a lot more ergonomic since you don't need to carry a case distinction around for every unwrap: an exception monad essentially has an implicit passthrough that says "if it's a value, apply the function, if it's an exception just keep that". You only need to "catch" the exception if you actually need the value. I'm this case the exception monad is not that different from annotating a function with "throws": your calling function either needs it's own throws (=error monad wrapper) in which case exceptions just roll through, or you remove the throws, but now need to handle the exception explicitly (=unwrap the monad).
- dev_hugepages 5mo agoUnrelated, but I was pleased at how fast the page opened: it felt pretty much instantaneous! I opened the network log, disabled cache and reloaded to see it only transferred 8kb. Keep up the good work!
- tome 5mo agoI don't understand why Zig's `Io` is a "monad". In fact I discussed that with the author of this article and the author of Zig here, but no conclusion was reached (https://news.ycombinator.com/item?id=46129568 https://news.ycombinator.com/item?id=46129568). But, flipping the script, if you want to see something like Zig's `Io` interface in Haskell then have a look at my capability system Bluefin, particularly Bluefin.IO. The equivalent of Zig's `Io` is called `IOE` and you can't do IO without it! https://hackage-content.haskell.org/package/bluefin-0.5.1.0/docs/Bluefin-IO.html https://hackage-content.haskell.org/package/bluefin-0.5.1.0/... Regarding custom allocators and such, well, that could fit into the same pattern, in principle, since capabilities/regions/lifetimes are pretty much the same pattern. I don't know how one would plug that into Haskell's RTS.
- george_____t 5mo ago> I don't understand why Zig's `Io` is a "monad". I don't see how it's true in any meaningful sense. It seems about the same as stating that any function is an example of the reader monad. The whole point of monads in programming languages is as an _abstraction_ that allows one to ignore internals like how the IO token is passed around. Maybe Zig is a language for people who are scared of abstraction. Otherwise they'd presumably be using something more powerful like Rust.
- noelwelsh 5mo agoAgreed, Zig's IO is closer to the effect handler / capability passing model. And by closer, I mean exactly the same [1]. However, it's related to monads by duality. A comonadic program is a program that depends on context, which captures the notion of passing capabilities around. [1] Languages designed around capability passing often have other features, like capture checking to ensure capabilities aren't used outside the scope where they are active. There are only two such languages I know of. Effekt (see https://effekt-lang.org/tour/captures https://effekt-lang.org/tour/captures) and Scala 3 (see https://docs.scala-lang.org/scala3/reference/experimental/cc.html https://docs.scala-lang.org/scala3/reference/experimental/cc...) However, this is not core to the idea of capability passing.
- psychoslave 5mo agoI guess that if a burrito can illustrate what is a monad, anything can be casted as a projection of a monad in some perspective. https://i.imgflip.com/65gu3j.jpg https://i.imgflip.com/65gu3j.jpg
- Uptrenda 5mo agothe autistic instinct to re-write every wheel in the latest shiny thing
- adrian_b 5mo agoWhile using "monads" in functional languages is a neat trick, I do not like them. In my opinion, the concept of automaton is fundamental and it deserves equal standing with the concept of function (even if it is a higher level concept that is built upon that of function). I believe that functional programming is preferable wherever it is naturally applicable, and most programs have components of this kind, but most complete application programs, i.e. which do input and output actions, are automata, not functions and it is better to not attempt to masquerade this with tricks that provide no benefits. Therefore, I prefer a programming language that has a pure functional subset, allowing the use of that subset where desirable, but which also has standard imperative features (e.g. assignment), to be used where appropriate.
- lmm 5mo agoYou can't just put assignment in a functional language though - you lose the ability to fearlessly refactor that's the whole point. You either need something like a stratified language (which I've never seen actually implemented, much less production-ready, as much as I like the design of Noether), or you use, well, monads.
- Paradigma11 5mo agoFor me monads are similar to inheritance. There are areas where one topic/functionality is dominant and it can really help to define a base class in a library or define a monad like for async. The moment you start to mix/compose things, things get ugly pretty fast.
- rienbdj 5mo agoQuestion for Zig users: Can comptime blow up compile times? Does it have arbitrary cutoffs like C++ template depth?
- resonancel 5mo agoYou can think of comptime (as of zig 0.16) as an interpreter that evaluates code with very limited optimization. So yes, naive use of comptime can definitely grind compilation to a halt. Zig tackles the halting problem a bit differently by putting the evaluation cutoff in userspace through the compiler builtin function `@setEvalBranchQuota`. You bump up the quota as you see fit.
- discreteevent 5mo ago> look at the era of software that garbage collectors have ushered in. Programs are bloated, slow, and wasteful compared to the literal super-computers that are running them. I don't think this even qualifies as correlation.
- hresvelgr 5mo agoI would encourage everyone remotely interested in Zig to have a look at Odin[1]. If like me, you read that article and found yourself muttering "what the hell," then you might appreciate Odin's simplicity and design consistency. I am definitely in the minority here, but I am not a fan of the kind of meta-programming that Zig and Rust offer, with Rust being especially atrocious. In the two decades I've been programming I can count on one hand the number of times meta-programming was an appropriate solution to a problem I had. Every time I reached for it, I got bit. There's a reason "when in doubt, use brute force" is sage advice, it may not be fast and glamorous, but it'll be a hell of a lot less opaque. [1] https://odin-lang.org/ https://odin-lang.org/
- christophilus 5mo agoSame. Meta programming is nice when it fits the problem, but most meta programming I’ve seen has been a net negative. Odin is also my favorite language in its class. It’s genuinely a gem.
- gravityblast 5mo agoProgrammers? What are they?
- suralind 5mo agoMy stack today is kinda nice but perhaps a bit odd: - Go - backend + CLIs - TypeScript - fronted, occasionally zx for more complex scripts - Nushell as my scripting language (I’ve been relentlessly using it everywhere I can instead of bash/zsh and man it is such an improvement) I heard so much good stuff about both Zig and Rust and would love to eventually get to know one of them.
- hootz 5mo agoNushell, from their website, looks a lot like PowerShell's idea of a shell, but less verbose.
- suralind 5mo agoYup. Which is kinda funny, because back when I was a young dev using Windows I never liked nor understood PS.
- stingraycharles 5mo ago> when I was a young dev … never understood PowerShell This makes me feel old.
- IdiotSavage 5mo agoPowerShell is not really that much more verbose. This is the equivalent of the nushell command by crabsand. dir | ? LastWriteTime -lt (Get-Date).AddDays(-21) | del
- metaltyphoon 5mo agoToo much casing changes, IMO
- IdiotSavage 5mo agoSorry. Fixed it for you. dir | ? lastwritetime -lt (get-date).adddays(-21) | del PowerShell is not case sensitive (but nushell and bash are).
- dev_l1x_be 5mo agoI am going to look at Zig after 1.0 is released. The current state is that you are playing catch up with language if you have any reasonable sized project in Zig. A new release might mean that you need to rewrite significant portion of your code.
- auggierose 5mo agoI am still hearing about Monads, but is it not the case that they have well-known flaws? And that is the reason why algebraic effects are interesting, because they don't have these flaws?
- gcr 5mo agoMonads are a math/organization pattern. What flaws do you mean?
- auggierose 5mo agoSee the comment by mmaniac.
- mmaniac 5mo agoThe biggest problem with monads that I am aware of is that they don't compose: if m1 and m2 are monads, then you can't automatically derive a new monad m3 where m1 (m2 a) and m3 a are equivalent. Monad transformers are one solution to this. This lets you write the composition rules for m2 once, and then reuse them for every m1. A solution, but boilerplatey. I don't understand algebraic effects quite as well, but my understanding is that they do simply compose.
- SomeHacker44 5mo agoI found this funny. I am not sure if it was intended that way! > Monads are not some kind of obscure math-y thing that only the big brains think are necessary. No, instead monads are a fundamental abstract algebraic description of imperative programming as a computational context. Yep, as a non-big-brainer, I definitely get it now. :)
- FrustratedMonky 5mo agoYou need to write a monad tutorial to really get it. https://news.ycombinator.com/item?id=47958106 https://news.ycombinator.com/item?id=47958106
- FrustratedMonky 5mo agoFrom article " Where the next Programming Language will come from? that beautifully described the sad state of things. His main point is that the incentives for programming language innovation are at best misaligned and at worst non-existent" Ok. Zig is great. But wont it still suffer from same headwinds as every other 'better' language. That industry wont adapt it? They have to much installed base and just want to hire Java/C#/etc...
- FrustratedMonky 5mo agoDo Zig's algebraic types, seem clunky. Or is this a false impression, and I'm just not getting it.
- king_geedorah 5mo agoA theme I found to be common here and in a lot of conversations in this vein on the site is the split between “We (software engineers) are programming actual computers whose behaviors we know” and “We (software engineers) are expressing business problems as abstract computation that should be independent of the computer on which they run.” The truth is somewhere in the middle but it’s interesting how many ostensibly technical disputes seem to come down to placement on this philosophical axis.