300 points · by Fudgel · 3y ago · 231 comments
The fact that Functions are Objects that can have properties/methods is supremely undervalued.
Are there other languages that do this so nicely? It's the perfect blend of OO and functional.
Programming is mostly about gradually figuring out the right design I find. JS/TS let's me evolve things naturally without big rewrites.
function foo() {}
function bar() {}
function baz() {}
const commands = [foo, bar, baz]
// Run commands
commands.forEach(x => x())
foo.help = 'This does something'
// Describe commands
commands.forEach(x => console.log(x.help))
// Add some state via closure.
const config = {}
function foo() { config.blah }
// Add some state using partials.
function _foo(config) { config.blah }
const foo = foo.bind(null, config)
I can flexibly do what I need, without ever having to define a class like `Command`, which I probably don't even know what it should be yet.This premature naming of things in OO creates so many dramas.
It avoids things like `VideoCompressor#compress()`, `VideoSplitter#split()`. You don't have to think: what state belongs in which class...you just call the function and pass it what it needs.
Here's some other languages that support objects as functions (although not necessarily functions as objects): https://en.wikipedia.org/wiki/Function_object
One of the canonical examples would be a net/http: A handler can both be a struct (or any other type really) that implements a serve method, or it can be a handler function that calls itself to satisfy the interface.
In Clojure you would achieve the thing you describe by attaching metadata on your function var. It being a Lisp, it also has macros so you can pretty much do anything.
Speaking of macros:
Clojure also implements CSP channels with macros in core/async, inspired by Go.
Channels are a very powerful construct that you might like a lot. With channels you can completely avoid the function coloring problem (callbacks, promises, async/await). Perhaps most importantly they decouple execution from communication.
So going back to your example, your commands could be producers that send their results on channels. They don't need to know what consumes w/e they make, nor do they need to hold on to it, mutate something, or call something directly.
Good analogies would be buses on motherboards, routers and switches in networks, conveyor belts, message queues in distributed systems and so on.
I'm not sure I'd like my functions to have properties (which gives them state and can alter what calling it does with the same arguments). A big benefit of FP is getting away from OO states. Perhaps the problems I work on aren't complex enough to benefit from them, or I simply make objects from classes.
It's just that there's now syntactic sugar for creating anonymous classes: `Foo foo = () -> "baz"` that automatically expands to an anonymous class that conforms to `Foo`. The compiler automatically assigns the method name for you.
There are lots of singletons in OO. I find it useful to add static metadata (not state) to them, without having to escalate them to a class. I guess Java has decorators for the same purpose. I'd really like decorators for functions in TypeScript though.
Or as I'm interpreting this, is sort of like documentation or information that could be used at runtime for code generation. Basically a shorthand for composing the function with its metadata. The nice thing about separation is that you know that when calling the function, there's no possible way for it to reference the metadata that is associated with it because it's composed externally.
Python, where everything is an object.
Example, I have some Redux helpers that are functions, but those functions also define a `.actionType` property. TypeScript handles that.
edit: accidentally wrote "object" instead of "function"
class IntAdder:
def __init__(self, x: int) -> None:
self.x = x
def __call__(self, y: int) -> int:
return self.x + y
def __str__(self) -> str:
return f"({self.x} + ??)"
add1 = IntAdder(1)
assert add1(3) == 4
print(add1)
# (1 + ??)
As mentioned in the sibling comment, you can define a Protocol which is analogous to an interface, so if you had a protocol like this: from typing import Protocol, TypeVar
T = TypeVar("T")
class ValueUpdater(Protocol[T]):
def __call__(self, y: T) -> T: ...
Then IntAdder would be considered a subclass of ValueUpdater[int] by the type checker. Demo: https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=strict&g... The fact that Functions are Objects that can have properties/methods is supremely undervalued.
Are there other languages that do this so nicely? It's the perfect blend of OO and functional.
Yes. C#. The equivalent are `Func` and `Action` types representing functions with a return and without a return. In fact, the JavaScript lambda expression looks awfully familiar to C#.One of the snippets below is C# and the other is TypeScript:
var echo = (string message) => Console.Write($"You said: {message}");
var echo = (message: string) => console.log(`You said: ${message}`);
The same signature in C# and TypeScript: var Apply = (Func<string, string> fn, string input) => fn(input);
var result = Apply(input => ..., "some_string");
var apply = (fn: (input: string) => string, input: string) => fn(input)
var result = apply(input => ..., input);
The C# can version can also be written like: var Apply = (Func<string, string> fn, string input) => fn(input);
var lowercase = (string input) => input.ToLowerInvariant();
var result = Apply(lowercase, "HELLO, WORLD");
For the curious, I have a small repo that shows just how similar JavaScript, TypeScript, and C# are: https://github.com/CharlieDigital/js-ts-csharpScreen grab of the same logic in JS/TS/C# showing the congruency: https://github.com/CharlieDigital/js-ts-csharp/blob/main/js-...
I often wonder how much of the code we write is actually doing something not possible in another language. Like runtime-specific, or low-level stuff. Most of the business logic...loops and if statements are rather similar.
const foo = () => doSomething;
foo.help = "this is a description of the function";
const commands = [foo];
// print help
commands.forEach(c => console.log(c.name, c.help || "No help is available for this function");
Presumably this isn't possible in C# because it's statically typed, so the object returned by "() => doSomething" can't be converted into one that supports adding more properties?.NET/C# has a `dynamic` type (aka `ExpandoObject`). That would be one way to do it (but would require casting to invoke). It's not exactly the same since you'd assign the `Func`/`Action` to a property of the `dynamic`. `dynamic` is generally avoided due to how easy it is to get into a pickle with it and also performance issues.
An alternate in this case is probably to return a tuple which I think is just as good/better.
Example:
var log = (object message) => Console.WriteLine(message);
var foo = () => log("Hello, World");
var fn1 = (foo, "This is the help text");
var commands = new[] { fn1 };
commands.ToList().ForEach(c => {
var (fn, help) = c;
log(fn.Method.Name);
log(help ?? "No help is available for this function");
});
https://dotnetfiddle.net/szxb9FThe tuple can also take named properties like this:
var log = (object message) => Console.WriteLine(message);
var foo = () => log("Hello, World");
var commands = new (Action fn, string? help)[] {
(foo, "This is the help text"),
(foo, null)
};
commands.ToList().ForEach(c => {
log(c.fn.Method.Name);
log(c.help ?? "No help is available for this function");
});
https://dotnetfiddle.net/oPK1d8Alternatively, use anonymous types:
var log = (object message) => Console.WriteLine(message);
var foo1 = () => log("Hello, World");
var foo2 = () => log("Hello, Neighbor");
var bar = new[] {
new {
doSomething = foo1,
help = "This is foo1's help text"
},
new {
doSomething = foo2,
help = "This is foo2's help text"
},
};
bar.ToList().ForEach(b => {
var (fn, help) = (b.doSomething, b.help);
fn();
log(help);
});
https://dotnetfiddle.net/KyBtgZThe next release of C# (12) will include named tuple types: https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
Very much looking forward to this since it gives you a lot of the same power of the JavaScript map/TS `Record`.
> ...because it's statically typed
While this is true, the `dynamic`/`ExpandoObject` is an oddity and lets you do weird things like multiple dispatch on .NET (https://charliedigital.com/2009/05/28/visitor-pattern-in-c-4...). But C# has a bunch of compiler tricks with regards to anonymous types that can mimic JS objects to some extent. The tuple type is probably a better choice in most cases, however.Python
compressor = lambda x: x / 2
compressor(5)
helpful_compressor = lambda x: x / 2
helpful_compressor.help = "compressor"
helpful_compressor(5)
helpful_compressor.help
Scala val compressor = (x: double) => x / 2
compressor(5)
object helpfulCompressor {
def apply(x: double) = x / 2
val help = "compressor"
}
helpfulCompressor(5)
helpfulCompressor.help
Ruby also has .call...but I can't remember it well enoughIn .net methods, properties, member variables, classes, etc. can have attached attributes that are objects. Attributes can be interrogated at runtime using reflection.
[MyAttrib(foo=42, bar="baz")]
class MyClass
{
}Their only reason to exist is to support a use case of a 1:1 relationship between classes and functional units (or methods and functional units, or parameters and functional units, etc.), which is almost always an 80% solution that makes the other 20% extremely hard and/or impossible. I would go so far as to say that every single use of an attribute is your own code begging you for a better design. Unfortunately you're sometimes stuck with them, but that's only because you're sometimes stuck with a framework that itself is begging its creators for a better design. I wonder if Attributes were never added to the language, if developers would have just made those better choices to begin with. From my vantage point, they were a clear mistake in a language that was otherwise very well designed.
They certainly are nothing like the ability to attach methods to functions. A better example of that kind of convenience in C# is extension methods, which you can certainly define on types like Func<T>. I love extension methods and miss them in every language that doesn't have them!
In Lua, you have regular, non-object functions, but you can also create a callable table using metamethods, and keep whatever data you have with it. Add to that the colon syntax sugar (implicit self vs explicit self) on table methods and I think you have a beautiful "opt-in" OO story without the unintuitive `this` business from JS.
What does TypeScript add in this scenario?
Does the example above even pass typecheck?
In fact I wish that constructor functions, and the class keyword never existed.
You can do the same with Object.create and a function closure, isn’t more verbose and it fits better with the mixed functional/oop approach of the language.
And advanced typelevel shenanigans you see in TS usually have their counterpart in Scala, especially in Scala 3's meta-programming features.
Everything is an object in Ruby as well
oh and burn npm to the ground please.
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.
https://medium.com/dartlang/dart-3-1-a-retrospective-on-func...
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.
They're still waiting on the do expression proposal for that (https://github.com/tc39/proposal-do-expressions), which has been in the bikeshedding stage for the past five years.
And the React example makes no sense, you can use a ternary and it is even shorter.
``` return ( <nav> <Home /> {loggedIn ? <LogoutButton /> : <LoginButton /> } </nav> ) ```
I've used it a bit but I haven't found it very boilerplatey in general, so I'm interested in learning what contexts you run into that.
I'm assuming you're using it with flutter?
-- 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.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!
(new Set([0, 1, 2])).values().map(x => x + 1).toArray()
You can also reduce, filter, find, etc.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.
Well, you could in theory get benefits by having optimizations based on the type declarations. This could be awkward to do when Typescript allows zero-runtime-cost interop with untyped JS anywhere and allows any value to be cast through the `any` type and then to any other type. If Typescript with these optimizations is still intended to execute in the same way as its untyped JS equivalent, then the optimizations all need to handle being opted out of when an unexpected value is received, in the same way optimizing runtime-type-tracking JS engines have to be able to abort out of their type-based optimizations. This optimization would be equivalent to pre-warming a JS engine's knowledge of runtime type information, which is an optimization that could be done for JS in general rather than by doing it just in the Typescript project through compiling to WASM.
Besides, enums (?) aside, and ignoring typechecking, compiling TS is really easy right now. Switching to WASM is a high ask.
People wanted a different language, they should have gotten more scripting languages in the browser. Not changing JavaScript so much that it's no longer JavaScript.
My fantasy for the past year has been, if I could magically program anything, bringing a compiler and spec wholesale into the world out of the void, I would create a new language (call it WebScript as a placeholder) that
- featured an ML style type system, ADTs, a type syntax nearly indistinguishable from TypeScript
- whose actual core language essentially resembled Kotlin or "Go with exceptions"
- compiled to WASM or JS as a compatibility bridge
Nothing radical. Nothing revolutionary. Just these things would be an immediate plus.
But maybe AssemblyScript is a good enough step towards that.
In browsers the Wasm runtime doesn't have access to the DOM APIs. So that's wishful thinking ATM.
const c = try { … } 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-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
} var something = (() => {
try {
return mayThrow()
} catch(SomeException ex) {
log.Info(ex);
return null;
} catch(Exception ex) {
log.Fatal(ex);
throw;
}
})();
Close enough?This was only ever true in V8, and hasn't been the case since 2017 with the optimizing compiler switch from Crankshaft to TurboFan.
Take a break before lecturing commenters on "guessing about performance is perhaps the most frequent anti-pattern in all programming" next time :)
Changing the way you program to fit what a JS compiler does or doesn't do is a fool's errand, IMO. The performance benefits are likely to be minimal, confusion for anyone else who has to touch the codebase is high.
Sure, you can check for everything. It often is more effective, but not prettier or easier to read and of course you also will miss cases.
If this is an actual concern (as in you have measured and try/catch is actually affecting something performance sensitive): you can most likely mitigate the impact by isolating the try/catch bodies in separate functions.
I haven’t verified this in every JIT, but I saw meaningful perf improvement in V8 for real world degenerate cases where the performance did actually matter and make a significant difference. But seriously, as always, measure before optimizing stuff like this! It might matter, but it seldom will for anything more than academic curiosity.
That's false. It used to be this way with Crankshaft but since 2017 we have Turbofan which solves this.
const c = myAsyncFun()
.catch(e => …)I suspect you could do something like:
const c = attempt(() => ... );
where attempt invokes the lambda, catches any exceptions, and does what you wantIf an exception is caught, the expression evaluates to what the catch block evaluates to. (Similar to having if/else be an expression). Of course if the exception isn't caught then it propagates so the expression doesn't take a value.
const c = (
()=> {
try: {...}
}
)() const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello, {s}!\n", .{"world"});
}https://medium.com/dartlang/dart-3-1-a-retrospective-on-func...
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)),
};Thats because c#s enum is not "closed"
I've programmed in Java, Python, C, C#, TypeScript, VHDL, and some other languages and they all fucking suck in some way.
If it was up to me, I would pick the best parts of the languages/ecosystems and make a Frankenstein language.
And anyway in the end, it's never the language. It's the ecosystem. Just because you can run Java on .NET doesn't mean you should -- because almost no one else does it your way and it's not worth the trouble maintaining some weird approach very few people use. You're never going to get help from library authors when it doesn't work on your weird setup.
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.
Surely that will change someday.
Edit: And inline pattern matching for values returned from expressions and function calls (similar to destructuring, but more powerful).
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.
Going between Rust and TS it is painfully obvious how much sth like tagged enums are missing, which can also be seen in this post.
I know of this [1] proposal for ADT enums which looks like it has stalled. Anyone know of other efforts?
[1] https://github.com/Jack-Works/proposal-enum/discussions/19
Also tsc is slow, sure, but only for the first run. Enabling `incremental` flag or using watch mode with `--transpile-only` usually brings compile time under 100ms, Making it practically indistinguishable from SWC or ESBuild.
Basically,
> Let's say TypeScript takes over 20 seconds to type-check a medium-sized program. That's not usually because it's JS, it's often because of types that cause a combinatorial explosion.
Also
> A different runtime can afford a lot (it sounds like parallelism and start-up time in this case) but I haven't seen a CPU-bound benchmark that supports the idea of a 20x all-up speed-up.
That's not to say they're useless though, they're good for fast hot-reload as you can have type-checking running in parallel.
<<<<<<<<T>>>>>>>>
Is basically a guaranteed headache
Written in Rust by the (lead?) dev of SWC
---
SWC (speedy web compiler) compiles TS to JS
STC (speedy type checker) checks TS types
[0] https://github.com/microsoft/TypeScript/pull/53463#issuecomm...
We had a very large Angular 10 project that we replaced with an NX Angular project late last year. We went from ~6 minute prod compile to around 20 seconds, recompile is lightning fast because it only builds your affected library. That is all without using the remote library cache feature where you can save compiled libraries to the cloud such that a user only builds the libraries they are changing ever.
TypeScript's compiler _is_ written in a compiled language.
(I think you are using "compiled" here as a euphemism—one that doesn't help anyone.)
The author uses a TypeScript subset to write a compiler to 32bit ARM assembly and explains that it almost looks like Pseudocode, so it is very accessible. A sentiment I can get behind, despite avoiding it in any case possible.
The book is split into two parts. The first implements a language interpreter in Java, and the second implements the same language by building a compiler to byte-code and also implements a byte-code VM in C. Every line of code in the implementation is referenced in the book.
export const run = <T>(f: () => T): T => f();
Now you can go: const inferred_type = run(() => {
switch(blah) {
...
}
}) const inferred = (() => "Hello")() // Inferred as "string"
If you really don't want to use an IIFE because you don't like the "()" at the end, you can just: const myFn = () => { switch(...) }
const inferred = myFn()For standard parser generator frontend, Ohm-js[1] is quite pleasant. I wouldn't recommend anyone reviews the offical tsc compiler, it's huuuge - instead there's mini-typescript[2] (in particular the centi-typescript branch[3]) which does a nice job illustrating how tsc is working.
[1] https://ohmjs.org/ [2] https://github.com/sandersn/mini-typescript/ [3] https://github.com/sandersn/mini-typescript/tree/centi-types...
Looking forward to GC an DOM access in WASM.
This led to the recommended advice of having a dedicated TS file where you pull all your external dependecies in and then re-export them locally. This felt worse than package.json (read: clunky not having a first-class system to list external dependencies). And this is in a project with minimal dependencies too - yet it still frustrated me. Plus my editor had no type info for any external imports. I then discovered import maps, but that was still hit and miss in my editor (Neovim mind you) with code completion, made worse by not having a clear way to import ohm-js. Not to mention having to explicitly list `--import-map` for every command and forgetting too often and then wondering why my code wasn't working. Just feels like it's on a roundabout path to reinventing package.json anyway, just with distributed packaging by default?
I'm not particularly concerned with security either, so having to list `--allow-x` and `--allow-y` got tiring very quick. At this point, I just felt like Deno was constantly trying to stop me from getting stuff done. I ended basically ditch most of the new stuff in Deno and was basically treating it a ts-node (thanks to the new NPM/Node compat feature) - but it had me off side now.
I knew Bun.sh has some rough edges in terms of compatibility, etc (which is fine as it's pre-v1)... but for writing a compiler: I'm mostly writing everything from scratch and just need to read/write from the filesystem which is definitely stable and well documented. Switching to Bun was painless and all of a sudden everything Just Worked™, ran faster and I can get back to actually working on my compiler. The only problem I've had with Bun is not being able to tweak the output the results of `bun test` (e.g. if one of the first tests fail, I have to keep scrolling back up through my big list of passing tests to see why it failed) - if Bun had a better error summary at the end of the test output I'd be set!
TLDR; As someone using NPM/node for over a decade, nothing in Deno "just worked" for me and instead blocked me at every turn and the lack of package management turned me off. I know there are sound and objective reasons for design decisions in Deno, but none of those things matter much _to me_. Bun, on the other hand, is intended as a drop-in replacement for Node, but faster and with native support for TypeScript which ticks all the boxes I need for this particular project. (FWIW I tried switching a Remix project to Bun and it didn't work and stuck with Node).
Ive personally decided to avoid visitor pattern bloat and Im waiting for closed enum feature in order to have compile time exhaustive check
implementation-centric: the language you are compiling is mostly fixed and/or defined by an external entity. You want to build the fastest compiler for this language, which emits the fastest code.
Of course, that one has been downvoted to -4 (as of now).
It's not the frontend glue-code kind of code. The inherently hard problem makes is fun for people who like to solve small puzzles.
It doesn't even have destructuring pattern matching!
At this point, even Java is better [1].
[1] https://github.com/tomprimozic/caya/blob/master/src/caya/Int...
But still, I think I'd rather use Rust. I'm pretty sure the code would be nicer (e.g. no need for the explicit tag field or for the visitor hack).
I like Typescript and Deno. But I'd still rather use Rust here.
I would love it someone made a RustScript though which would be basically Rust but with arbitrary precision integers, garbage collection etc. (but still value semantics).