7 ms·
Is that really suprising? Typescript is yet another language that has, kicking and screaming, picked up most of the ML featureset. I'd expect it to be, well, fi
by lmm 3y ago
Is that really suprising? Typescript is yet another language that has, kicking and screaming, picked up most of the ML featureset. I'd expect it to be, well, fine; the lack of real pattern matching is a pain, so it's going to be inferior to OCaml, but fine, no different from using C# or Swift or Dart or Kotlin or something of that ilk.
- thebears5454 3y agoNaively, I would have guessed it being harder than C#
- paddim8 3y agoI would think C# is easier for this due to having proper (and very convenient) pattern matching.
- zkldi 3y agoC# doesn't have anything resembling proper pattern matching. C#s pattern matching is akin to a marginally improved switch or if/else-if chain. C#s pattern matches aren't exhaustive, and the compiler doesn't properly check them at all.[0] There are no proper sum types in C#, so 80% of the point isn't even there. enum Season { Spring, Summer, Autumn, Winter } ... int PatternMatch(Season season) => season switch { Season.Spring => 1, Season.Summer => 2, Season.Autumn => 3, Season.Winter => 4, // compiler can't prove the above code is exhaustive because no proper sum types // compiler needs nonsensical branch here that diverges _ => throw new ArgumentException("Invalid enum value for command", nameof(command)), };
- hardware2win 3y ago>compiler can't prove the above code is exhaustive because no proper sum types Thats because c#s enum is not "closed" https://github.com/dotnet/csharplang/issues/3179 https://github.com/dotnet/csharplang/issues/3179
- deleted 3y ago[deleted]
- paddim8 3y agoThese things are not about pattern matching but about other language features.
- IshKebab 3y ago> picked up most of the ML featureset It really hasn't. In this very post he had to use a visitor to work around the fact that switch isn't an expression. JavaScript's support for iterators is also weirdly shit. It has `.map()` but that only works on arrays. You can't map an iterator!
- andyferris 3y agoI think there’s an iterator proposal out there for JS with generic map, filter, etc.
- bakkoting 3y agoYou can now! The iterator helpers proposal is stage 3 and shipping in Chrome. (new Set([0, 1, 2])).values().map(x => x + 1).toArray() You can also reduce, filter, find, etc.
- moonchrome 3y agoThat's some very high level view - in reality even tough those languages are in similar categories the experience would be vastly different : TypeScript - powerful type system but shit underlying stdlib and language (no pattern matching/switch expressions) Dart - worse than TS because the object model is closed - so no dynamic freedom, but the type system and expressions are weaker then the rest. Also 0 meta programming facilities - Java level of boilerplate and code generators C# - closest to ML featureset out of the mentioned, but unlike TS doesn't have sum types which will make a lot of things more tedious.
- pja 3y agoIf you’re going to use C# for a compiler, why not go the whole hog & use F#?
- moonchrome 3y agoNo argument from me, just saying lumping in all those languages together sounds reasonable in theory, in practice they are very far apart. You'll probably have similar overlap between C# and F# implementations as you would with say TypeScript - they are just that different in practice IMO.
- delta_p_delta_x 3y agoI was going to mention F#. The parent and grandparent comments mention C# and ML, and the intersection of the two is... F#.
- crooked-v 3y ago> no pattern matching/switch expressions They're still waiting on the do expression proposal for that (https://github.com/tc39/proposal-do-expressions https://github.com/tc39/proposal-do-expressions), which has been in the bikeshedding stage for the past five years.
- yunohn 3y agoI’m not clear on the benefits of this proposal over just using anonymous functions. Some of the examples just seem contrived. And the React example makes no sense, you can use a ternary and it is even shorter. ``` return ( <nav> <Home /> {loggedIn ? <LogoutButton /> : <LoginButton /> } </nav> ) ```
- baq 3y agoThe biggest expressivity pain point in practice for me is try/catch not being an expression, so I can’t do const c = try { … }
- lovasoa 3y agoWith async code, there is const c = myAsyncFun() .catch(e => …)
- WorldMaker 3y agoThat leaves c as Promise which was not the type they were looking for. You'd still have to unwrap the promise and deal with the result or rejection. The easiest way to do that is to use await, and if you are using await you'd be better off using try {} catch {} around the async function than .catch().
- jve 3y agoYes! This just drives me crazy: string something = null; try { something = mayThrow(); } catch (SomeException ex) { log.Info(ex); } catch (Exception ex) { log.Fatal(ex); throw; } if (something != null) { ... } Would be actually nice if it had F#'s try...with https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/exception-handling/the-try-with-expression https://learn.microsoft.com/en-us/dotnet/fsharp/language-ref... and would allow us something like: var something = try { mayThrow() } with (SomeException ex) { log.Info(ex); } with (Exception ex) { log.Fatal(ex); throw; } Or some way to do pattern matching on exceptions for switch expression. var something = mayThrow() switch { (SomeException ex) => { log.Info(ex); return null; } (Exception ex) => { log.Fatal(ex); throw; } var passThru => passThru }
- scotty79 3y agovar something = (() => { try { return mayThrow() } catch(SomeException ex) { log.Info(ex); return null; } catch(Exception ex) { log.Fatal(ex); throw; } })(); Close enough?
- dejawu 3y agoI'm quite fond of this library for pattern matching; it's a staple in all my new projects. https://github.com/gvergnaud/ts-pattern https://github.com/gvergnaud/ts-pattern
- jillesvangurp 3y agoI've done a bit of typescript and kotlin-js. It always strikes me how close those two languages are. Yes there are lots of differences but they aren't that different and you can transition from one to the other pretty easily. I have my preferences (kotlin) but I can work with both. IMHO typescript could just cut loose from its javascript compatibility. Why not compile it to wasm instead of transpiling it to javascript? Kotlin is in the process of adding a wasm compiler and they already have a js transpiler. The same code results in a lot smaller binaries and loads a lot faster in wasm form. Browser Javascript is not a great compilation target. And who cares what the minified crap that loads in the browser looks like? The only reason for backwards compatibility is allowing javascript projects to easily transition to typescript. But that's increasingly less relevant now that a lot of projects start out being typescript from day 1. Of course, Assembly script is already a thing. But why not make that a bit more official? It wouldn't surprise me to see people doing a lot of web development in languages like that in a few years.
- orra 3y agoI'm afraid that's wishful thinking. JS compatibility is core to the TypeScript ethos, regardless of TypeScript's own popularity. Besides, enums (?) aside, and ignoring typechecking, compiling TS is really easy right now. Switching to WASM is a high ask.
- horsawlarway 3y agoJS compatibility is core to Typescript's own popularity.
- deleted 3y ago[deleted]
- flohofwoe 3y ago"Modern" Javascript essentially is Typescript without the type hints (e.g. if you ignore the historical baggage, JS is actually a fairly decent language).
- 3y ago
- xvilka 3y agoThis is why once WebAssembly more polished and more common, languages like JS and TS could become obsolete since proper, more powerful languages will suddenly become a valid choice for Web.
- mbork_pl 3y agoYou mean, like C and its derivatives became obsolete once successors to PDP machines were built? ;-)
- flohofwoe 3y agoAny non-toy WASM application running in browsers will almost certainly end up as a hybrid WASM/JS application, just because you can't call directly from WASM into browser APIs, and even if the JS shim is "hidden from view", sometimes it's either more convenient or even more performant to write more than just a thin API shim in Javascript, especially for asynchronous code or to avoid redundant copying of large data blobs in and out of the WASM heap.
- LudwigNagasena 3y ago> just because you can't call directly from WASM into browser APIs Surely that will change someday.
- flohofwoe 3y agoYou are still limited by the fact that browser APIs are mainly designed for usage with Javascript, and those Javascript APIs usually don't map all that well to languages used with WASM (which typically use the "C ABI" for FFI). There is zero chance that each web API will get a second API which is compatible with "C calling conventions". There is a (now inactive) "interface-types" proposal, which has dissolved into "component-types", but this scope-creep definitely is already quite concerning: https://github.com/WebAssembly/interface-types https://github.com/WebAssembly/interface-types
- andsoitis 3y ago> This is why once WebAssembly more polished and more common, languages like JS and TS could become obsolete since proper, more powerful languages will suddenly become a valid choice for Web. JavaScript and TypeScript are not "proper" languages? Different languages are powerful in different use case dimensions (tradeoffs), and the typical client-side web programming has a very very strong UI angle, which many "more powerful" languages that I am going to guess you have in mind are less adept at.
- pjmlp 3y agoC# and Swift have pattern matching.
- troupo 3y agoIt's more limited than what you'd ideally want: pattern matching in function definitions. This makes walking ASTs a breeze. Edit: And inline pattern matching for values returned from expressions and function calls (similar to destructuring, but more powerful).
- pjmlp 3y agoI would say what C#11 does is already quite good, likewise for Swift. Perfection is the enemy from good. Those I can use at work, ML derived languages not, even F# is an uphill battle in most shops.
- chpatrick 3y agoType-refining if in TypeScript is good enough for pattern matching if you ask me.
- graftak 3y agoThe TypeScript type system meta programming actually does pattern matching very well, it’s just the underlying JS runtimes that can’t, there is a proposal for it though; https://github.com/tc39/proposal-pattern-matching https://github.com/tc39/proposal-pattern-matching.
- DrScientist 3y agoDart pattern matching? https://medium.com/dartlang/dart-3-1-a-retrospective-on-functional-style-programming-in-dart-3-a1f4b3a7cdda https://medium.com/dartlang/dart-3-1-a-retrospective-on-func...
- madeofpalk 3y agoLack of pattern matching is annoying, but Typescript's tagged unions and type narrowing from if-statements are a good substitude and make for a very pleasent time traversing ASTs. C# has it's own way to express similar data structures (with subclasses and interfaces), but I find unions+narrowing much more natural in Typescript.
- retrac 3y agoSome crude snippets from a Pascal-C (I never could decide) self-educational compiler/toy I wrote a while ago (in Haskell): -- a parser function that matches on { ... } returning ... -- can be combined with other parsers braces = (symbol "{") `between` (symbol "}") ... -- a statement is a controlFlow or a declaration or an assignment statement = controlFlow <|> declaration <|> assignment -- a block is either 1 or more statements surrounded by { ... } -- or a single statement. block = (braces $ many statement) <|> statement ... -- An expression is a number, or a variable, or a binary operation -- derive functionality to print and test equality of these values. data Expr = Num Int | Var Variable | DualOp Op Expr Expr ... deriving (Show, Eq) ... foldConstants (DualOp Add (Num a) (Num b)) = Num (a + b) ... Parser combinators (parser functions that take other parser functions and return more complex combined parser functions) with enough syntactic sugar can express BNF-like grammars directly as code. And ML-style list and pattern matching operations are very expressive for operating on the intermediate representation.