52
submitted 20 hours ago* (last edited 18 hours ago) by little_ferris@programming.dev to c/rust@programming.dev

If we were to create a Rust version of this page for Haskell, what cool programming techniques would you add to it?

top 36 comments
sorted by: hot top controversial new old
[-] solrize@lemmy.world 1 points 2 hours ago

Here's another Haskell example where I'd be interested to see a Rust counterpart. It's a red-black tree implementation where the tree invariants are enforced by types. The code would less ugly with more recent GHC features, but same idea.

https://gist.github.com/rampion/2659812

https://old.reddit.com/comments/ti5il

[-] Infernaltoast@programming.dev 4 points 8 hours ago* (last edited 8 hours ago)

You can manually implement PartialEq and Eq on an Enum that implements Hash to manually determine how the hashmap keys override/collide with one another.

[-] tatterdemalion@programming.dev 3 points 8 hours ago

One thing I like a lot about Rust is that it rarely does blow my mind.

But one crate that actually did blow my mind is corosensei. It's not Rust per se that is so crazy here, but the way it's essentially implementing a new language feature with assembly code. This is how you know Rust really is a systems programming language. I invite you to read the source code.

[-] tuna@discuss.tchncs.de 9 points 12 hours ago

Something i didnt know for a long time (even though its mentioned in the book pretty sure) is that enum discriminants work like functions

#[derive(Debug, PartialEq, Eq)]
enum Foo {
    Bar(i32),
}

let x: Vec<_> = [1, 2, 3]
    .into_iter()
    .map(Foo::Bar)
    .collect();
assert_eq!(
    x,
    vec![Foo::Bar(1), Foo::Bar(2), Foo::Bar(3)]
);

Not too crazy but its something that blew my mind when i first saw it

[-] tatterdemalion@programming.dev 3 points 8 hours ago

Clippy will warn you if you don't use this feature.

[-] Ephera@lemmy.ml 7 points 12 hours ago

This works with anything that one might call "named tuples".

So, you can also define a struct like so and it'll work:

struct Baz(i32);

On the other hand, if you define an enum variant with the normal struct syntax, it does not work:

enum Foo {
    ...
    Qux { something: i32 } //cannot omit braces
}
[-] barsoap@lemm.ee 1 points 10 hours ago* (last edited 10 hours ago)

Named function arguments would occasionally be nice to have instead of the single n-tuple they take now. Currently I'm more or less playing a game of "can I name my local variables such that rust-analyzer won't display the argument name when I stick them into functions (because they're called the same)).

[-] Ephera@lemmy.ml 1 points 8 hours ago

Yeah, I do miss those, too, although I've noticed that I'm becoming ever more consistent with just naming my variables like the type is called and that works out nicely in Rust, because then you can also leave out the field name when filling in a struct with named fields. I'll often have named my function parameters the same name that I ultimately need to pass into structs fields.

At this point, I'm secretly wondering, if a programming language could be designed where you don't normally fill in variable names, but rather just use the type name to reference each value.
For the few cases where you actually do have multiple variables of the same type, then you could introduce a local (type) alias, much like it's currently optional to add type annotations.
Someone should build this, so I don't have to take on another side project. πŸ™ƒ

[-] little_ferris@programming.dev 1 points 11 hours ago

Yea it's like when we writeSome(2). It's not a function call but a variant of the Option enum.

[-] barsoap@lemm.ee 2 points 10 hours ago

Enum constructors are functions, this typechecks:

fn foo<T>() {
    let f: fn(T) -> Option<T> = Some;
}

I was a bit apprehensive because rust has like a gazillion different function types but here it seems to work like just any other language with a HM type system.

[-] little_ferris@programming.dev 1 points 9 hours ago

Woah. That's quite interesting. I didn't know that.

[-] SorteKanin@feddit.dk 22 points 15 hours ago

Not exactly the same thing but this is still pretty funny. This is code that is technically 100% legal Rust but you should definitely never write such code πŸ˜….

[-] silasmariner@programming.dev 1 points 5 hours ago

This is excellent content

[-] barsoap@lemm.ee 2 points 8 hours ago

That makes complete sense. Ranges implement fmt::Debug, .. is a range, in particular the full range (all values) ..= isn't because the upper bound is missing but ..=.. ranges from the beginning to the... full range. Which doesn't make sense semantically but you can debug print it so add a couple more nested calls and you get a punch card.

I totally didn't need the Rust playground to figure that out.

[-] AsudoxDev@programming.dev 9 points 14 hours ago
[-] SorteKanin@feddit.dk 17 points 14 hours ago

It's a test for the compiler which ensures that these legal yet extremely weird expressions continue to compile as the compiler is updated. So there is a purpose to the madness but it does still look pretty funny.

[-] Ephera@lemmy.ml 15 points 15 hours ago

A cool thing you can do, is to store values of all kinds of types in a big HashMap, basically by storing their TypeId and casting them to Box<dyn Any> (see std::any).
Then you can later retrieve those values by specifying the type (and optionally another ID for storing multiple values of the same type).

So, you can create an API which is used like this:

let value = MyType::new();
storage.insert(value);
let retrieved = storage.get::<MyType>();
assert_eq!(retrieved, value);

There's various ECS storage libraries which also implement such an API. Depending on what you're doing, you might prefer to use those rather than implementing it yourself, but it's not too difficult to implement yourself.

[-] SorteKanin@feddit.dk 8 points 15 hours ago

There's a crate for it too: anymap2

[-] Buttons@programming.dev 2 points 14 hours ago

What if I specify the wrong type? let retrieved = storage.get::<SomeOtherType>();?

Is it a runtime error or a compile time error?

[-] Buttons@programming.dev 5 points 14 hours ago
[-] Ephera@lemmy.ml 1 points 14 hours ago* (last edited 14 hours ago)

Well, you would determine the TypeId of SomeOtherType, then search for that as the key in your HashMap and get back a None, because no entry exists and then you'd hand that back to the user.
I guess, my little usage example should've included handling of an Option value...

So, it's only a runtime error, if you decide to .unwrap() or similar.

[-] silasmariner@programming.dev 13 points 19 hours ago

Rust isn't really a language that lends itself to terse point-free functional idioms... The sort of examples I might want to share would probably require a bit more context, certainly more code. Like I think type guards and arena allocation are cool and useful tricks but I don't think I could write a neat little example showing or motivating either

[-] little_ferris@programming.dev 7 points 18 hours ago

Yeah I don't mean just terse functional idioms. Any programming technique that blew your mind the first time you came across it would qualify.

[-] silasmariner@programming.dev 3 points 16 hours ago

Type guards, then :) very cool, much compiler power, love it

[-] little_ferris@programming.dev 2 points 16 hours ago
[-] naonintendois@programming.dev 5 points 15 hours ago

Maybe they're referring to "where clauses"?

[-] silasmariner@programming.dev 2 points 12 hours ago

Indeed I am. Forgot the name, lol, not worked with rust for a few months πŸ˜…

[-] solrize@lemmy.world 4 points 18 hours ago* (last edited 17 hours ago)

I'd like to see a Rust solution to Tony Morris's tic tac toe challenge:

https://blog.tmorris.net/posts/scala-exercise-with-types-and-abstraction/index.html

His rant about it is here:

https://blog.tmorris.net/posts/understanding-practical-api-design-static-typing-and-functional-programming/

I did a Haskell GADT solution some time back and it's supposed to be doable in Java and in C++. Probably Rust too. I wonder about Ada.

[-] silasmariner@programming.dev 2 points 4 hours ago* (last edited 4 hours ago)

That doesn't look like a particularly difficult challenge? Like, it's just an implementation game, move returns a data type that you write yourself

Edit: I suppose there's life in that kind of ambiguous variation though

[-] solrize@lemmy.world 1 points 2 hours ago

Well if there isn't already a Rust version on github, it could be cool to add one. A few other languages are already there.

[-] LPThinker@lemmy.world 5 points 14 hours ago

This could be done almost trivially using the typestate pattern: https://zerotomastery.io/blog/rust-typestate-patterns/.

[-] solrize@lemmy.world 1 points 5 hours ago* (last edited 5 hours ago)

Neat that looks interesting. There's a similar Haskell idiom called session types. I have a bit of reservation about whether one can easily use Rust traits to mark out the permissible state sets that an operation can take, but that's because I don't know Rust at all. I do remember doing a hacky thing with TypeLits in Haskell to handle that. Basically you can have numbers in the type signatures and do some limited arithmetic with them at type level. I'd be interested to know if that is doable in Rust.

[-] someacnt_@lemmy.world 1 points 16 hours ago

The haskell examples look more like an arcane wizardry.

My favorite example of haskell arcane wizardry is lΓΆb. It's mentioned in this list but not really done justice imo.

[-] little_ferris@programming.dev 2 points 16 hours ago* (last edited 16 hours ago)

πŸ˜‚ Ikr!

[-] BB_C@programming.dev 0 points 13 hours ago* (last edited 13 hours ago)

Can't think of anything.
The novelty must have worn off over time.
Or maybe my mind doesn't get blown easily.

this post was submitted on 16 Oct 2024
52 points (96.4% liked)

Rust

5867 readers
94 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS