3 ms·
Er, don't Haskell's head and (!!) functions default to throwing an exception? $ ghci Prelude> let a = [3, 4, 5] Prelude> a !! 0 3 Prelude>
by geofft 7y ago
Er, don't Haskell's head and (!!) functions default to throwing an exception?
$ ghci
Prelude> let a = [3, 4, 5]
Prelude> a !! 0
3
Prelude> a !! 3
*** Exception: Prelude.(!!): index too large
Prelude> head []
*** Exception: Prelude.head: empty list
I don't think Haskell is really different from Rust in this respect. Both have a wrapper type for optional values with good syntax, but in both, there's still some syntax so common operations sometimes choose to skip it.
In fact, Hoogle doesn't seem to find me a function like Rust's .get() in the standard library, just a handful of third-party packages: https://hoogle.haskell.org/?hoogle=%5Ba%5D+-%3E+Int+-%3E+Maybe+a&scope=set%3Astackage https://hoogle.haskell.org/?hoogle=%5Ba%5D+-%3E+Int+-%3E+May...
- EvilTerran 7y ago> Hoogle doesn't seem to find me a function like Rust's .get() in the standard library In practice, you don't really need one - the safe alternative to "xs !! n" is pattern-matching on the result of "drop n xs", as that's [] if xs has ≤n elements: https://www.haskell.org/onlinereport/standard-prelude.html#$vdrop https://www.haskell.org/onlinereport/standard-prelude.html#$...
- masklinn 7y ago> In practice, you don't really need one - the safe alternative to "xs !! n" is pattern-matching on the result of "drop n xs", as that's [] if xs has ≤n elements: Great so instead of `xs !! n` you're supposed to write case drop n xs of [] -> … x :: _ -> … that seems… less than likely?
- geofft 7y agoSure, that seems syntactically more cumbersome than 'if let Some(foo) = xs.get(n)' or 'xs.get(n).map(|foo| ...)' in Rust, but yes, you can do it. As I said, because both the Rust and Haskell versions are more cumbersome than using the version that raises an exception/panics, both Rust and Haskell's standard libraries choose to give you a syntactically-easier alternative that isn't a total function. All I'm saying is that Haskell doesn't seem to do anything different here - Rust has incorporated the lessons from Haskell's type system. (As someone who fell in love with Haskell a long time ago but never got to use it professionally, this is basically why I like Rust.) Is there something Haskell does that Rust does not do? I'm not trying to say Haskell is insufficient - I'm just refuting the claim that Rust is insufficient and should act more like Haskell.
- EvilTerran 7y agoSure, I don't disagree - I meant only to add context for anyone reading who was unfamiliar with Haskell, lest they come away with the impression that the lack of a .get()-equivalent was some kind of egregious oversight.
- olalonde 7y agoThis was posted on /r/rust a couple days ago: https://notes.iveselov.info/cheatsheet-rust-option-vs-haskell-maybe https://notes.iveselov.info/cheatsheet-rust-option-vs-haskel...