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.
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.
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.
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.
interface SomethingCallableWithAnExtraProperty {
// This means you can call it like a function.
(args: Whatever): SomethingReturned
// And since it's an interface, you can still do interface-y things
anotherProperty: string
} 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...[1]: https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-... [2]: https://kangax.github.io/compat-table/es6/#test-proper_tail_...
Is it the fact that you have to give it a name? If so I'd say just using some generic name like `{f,fn,func(tion),callback,etc}` is fine (at least as much as an anonymous function is), and to me would usually be more readable than an inline definition of a multi-statement lambda would be.
Or maybe it's the fact that lambdas are allowed in the first place, so people are going to use them, and then when you want to debug a lambda you'll probably have to go to the trouble of changing it to a function? That is a fair complaint if so.
In any case I can see how it could be annoying if you're more used to a language full of complex inline lambdas.
It's much easier to follow the control flow with hoisting. I see `run()` being called, and then I want to know what it is. In other languages you are usually seeing a huge bunch of inline functions and then asking: okay, but when and how is this actually called?
def foo():
def run():
print("hi")
run()
function foo() {
run()
function run() {
console.log('hi')
}
}moreover... basically any half-decent programmer text editor has an outline with the list of functions, so this point may be moot in any way
map(lambda x: (x := func1(x), func2(x), None)[2], gen())
This sets x to func1(x), then executes func2, then leaves None in place of the element in the map iterable. (of course you could do the same with a list comprehension, you wouldn't even need the lambda in that case, and good python would _actually_ be a for loop.)What does TypeScript add in this scenario?
Does the example above even pass typecheck?
Everything is an object in Ruby as well
In .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!
Here's some other languages that support objects as functions (although not necessarily functions as objects): https://en.wikipedia.org/wiki/Function_object
And advanced typelevel shenanigans you see in TS usually have their counterpart in Scala, especially in Scala 3's meta-programming features.
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}`);
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-...
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.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.
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.
oh and burn npm to the ground please.
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.
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.
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 enough
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.
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.