7 ms·
When if is just a function
- icepat 1y agoIs this just a quirk in my display, or are all the code blocks in this formatted like a CIA black highlighter
- middayc 1y agoI checked in Firefox and Chrome (on Linux) and code samples look OK to me. What browser/OS are you using. Maybe send me a screenshot at janko dot itm at gmail.
- blauditore 1y agoSame here. I guess it's an issue with (system) dark theme (you can simulate that in dev tools. Android here, so must be Chrome.
- middayc 1y agoI fixed it thanks! I was able to activate dark more in Firefox on desktop and find problems with CSS.
- icepat 1y agoThis is on FF for me. Specifically Zen, which is FF based.
- singlow 1y agoIt's only a problem if I have my browser set to use dark theme or system theme and my system theme is dark if I switch it to light theme. Everything looks good. So most likely he's using some kind of CSS framework that's automatically responding to the dark theme, but other styles that he's hand coded are not compatible with it
- middayc 1y agoThank you all for heads up! I was playing with CSS and didn't test the dark mode. I think it's fixed now.
- blahgeek 1y agoSeems lispy
- taeric 1y agoWithout the discussion of applicative-order versus normal-order.
- middayc 1y agoBTW: In Lisps, if is still a special form / macro, because in Lisp lists are evaluated by default, in Rebols if can be a function because blocks (lists) aren't evaluated by default.
- kazinator 1y agoYou can rarely successfully generalize about languages in the Lisp family. :) TXR Lisp: (relevant to this article) there is an iff function that takes functional arguments. Square the odd values in 0 to 9: 1> (mapcar [iff oddp square use] 0..10) (0 1 2 9 4 25 6 49 8 81) The use function is a synonym of identity: i.e. just use the incoming value as-is Square the even ones instead by inverting oddp with notf: 2> (mapcar [iff [notf oddp] square use] 0..10) (0 1 4 3 16 5 36 7 64 9) Get rid of use with iffi: a two-argument iff with an implicit identity else: 3> (mapcar [iffi oddp square] 0..10) (0 1 2 9 4 25 6 49 8 81) Now about the point about Lisps and if: the regular if operator with value and expression arguments has a companion if function: 4> (special-operator-p 'if) t 5> (fboundp 'if) t Unlike in some other dialects like Common Lisp, a symbol can have a binding in the macro or operator space, and in the function space at the same time. But this if is not useful control. It's useful for things like being able to map over a function-like facsimile of the if operator. E.g. take an element of the (a b c d) or (x y z w) list depending on whether the leftmost list has a nil or t: 6> [mapcar if '(nil t nil t) '(a b c d) '(x y z w)] (x b z d) In the reverse direction, being able to write a macro for a function function exists, allows for ordinary macros to be "compiler macros" in the Common Lisp sense: provide optimizations for certain invocations of a function. This dialect is not even "weird"; overall it is Common-Lisp-like. Right down to the multiple namespaces, which is why the [...] syntax exists for referring to functions and variables in a combined virtual namespace.
- veqq 1y agoCombinatory programing offers functional control flow. (Here is a straight forward explanation: https://blog.zdsmith.com/series/combinatory-programming.html https://blog.zdsmith.com/series/combinatory-programming.html ) I was inspired to write `better-cond` in Janet: (defn better-cond [& pairs] (fn [& arg] (label result (defn argy [f] (if (> (length arg) 0) (f ;arg) (f arg))) # naming is hard (each [pred body] (partition 2 pairs) (when (argy pred) (return result (if (function? body) (argy body) # calls body on args body))))))) Most Lisps have `cond` like this: (def x 5) (cond ((odd? x) "odd") ; note wrapping around each test-result pair ((even? x) "even")) Clojure (and children Fennel and Janet) don't require wrapping the pairs: (def x 5) (cond (odd? x) "odd" (even? x) "even") My combinatoresque `better-cond` doesn't require a variable at all and is simply a function call which you can `map` over etc.: ((better-cond (fn [x] (> 3 x)) "not a number" # just showing that it can accept other structures odd? "odd" even? "even") 5) Of course, it can work over multiple variables too and have cool function output: (defn recombine # 3 train in APL or ϕ combinator [f g h] (fn (& x) (f (g ;x) (h ;x)))) (((better-cond |(function? (constant ;$&)) |($ array + -)) recombine) 1 2) # |( ) is Janet's short function syntax with $ as vars
- roxolotl 1y agoDo you have any recommendations for a language where you _have to_ use these concepts. I love playing with them but I find that unless i’m paying a lot of attention in most cases I fall back to a less functional style even in a language like Janet. I’d love to find a language where you largely have to use these combinatorial logic style functions so I can’t just default back to other styles.
- veqq 1y agoJ and BQN (APL has off-ramps...) https://code.jsoftware.com/wiki/Essays/Tacit_Expressions https://code.jsoftware.com/wiki/Essays/Tacit_Expressions https://mlochbaum.github.io/BQN/doc/tacit.html https://mlochbaum.github.io/BQN/doc/tacit.html and https://mlochbaum.github.io/BQN/doc/control.html https://mlochbaum.github.io/BQN/doc/control.html Forth, Factor and Uiua (which combines the above approach) don't use these concepts yet are also inherently point-free, and without lambdas so you definitely wouldn't be able to rely on functional techniques!
- jrochkind1 1y agoSmalltalk, anyone? I guess the OO version.
- sebastianconcpt 1y agoYeah, here. They should know the feeling of booleans as instances and ifTrue: ifFalse: as methods. But for us is such an obvious thing that isn't really something too remarkable. It normalized language awesomeness.
- middayc 1y agoThere is a language https://sprylang.se/index.html https://sprylang.se/index.html which started more as Rebol and moved towards Smalltalk.
- ivanjermakov 1y agoThe drawback is that this approach elevates code blocks to first class. It means that there is a semantical difference between a value that is a block and a value that is a result of a block. This reduces code clarity, because now block def/result is discriminated by context instead of syntax. - closures get tricky, i.e. having outer scoped variables within a block - inter-block operators still need special care, e.g. return should return from a function or a nearest block, same for break/continue/etc.
- danlitt 1y agoThis criticism seems at face value to also apply to first-class functions, which I thought was a totally uncontroversial pattern. Do you dislike those too?
- ivanjermakov 1y agoFirst-class functions are problematic too[1], but function is always a definition. While code block is usually meant to be executed right away. [1]: https://github.com/ziglang/zig/issues/1048 https://github.com/ziglang/zig/issues/1048
- em-bee 1y agocan you please explain what the actual problem here is? i am trying to read through that issue discussion, but i am not quite getting what makes first-class functions problematic. as far as i am concerned, not having first-class functions would be a serious limitation to a language that would make me avoid using that language for anything serious.
- hatthew 1y agoThis is interesting, but I'm not convinced it's better than the python it's being compared to. Memorizing and understanding the behavior of functions that perform control flow seems no easier than memorizing and understanding hardcoded syntax/keywords. The additional flexibility of making everything a first-class citizen allows people to write code that is too clever for its own good. I could be wrong but I think there is a broad consensus that reflection is a Bad Idea. Open to being convinced otherwise (tangent but related, aren't the "Loops" and "Iteration" examples given for python literally the exact same syntax, with the exception of changing how the iterable is generated?)
- Nevermark 1y ago> I could be wrong but I think there is a broad consensus that reflection is a Bad Idea. Reflection may be bad in practice for other reasons/conditions, but the lack of simple/minimal/regular primitive conventions in many languages, makes reflection a basket of baddies. The code blocks of Rye seem comparable to closures, which is a sensible thing to have. Once all code blocks are closures, there are fewer concepts to wrangle, and functional control makes excellent sense.
- hatthew 1y agoThat makes sense, thanks!
- hshdhdhehd 1y agoI agree. In any somewhat functional language (I.e. all the mainstream ones) you can wrap "if" in a function if you please. E.g. function funif (b, f) { return (b && f()) } If you want to do clever stuff. I never feel the need as I would rather abstract over bigger things.
- middayc 1y agoYou can do it, but that is not how the (default) control structures work in those languages. There is usually also some syntax cost.
- davidw 1y agoSeems a bit like Tcl, which lets you create your own control structures like that.
- pwg 1y agoOr redefine the language provided 'if' statement, in the case that one wanted to do so.
- middayc 1y agoYou can't really redefine if because everything is a constant, but you can define if in your own context yes.
- cmacleod4 1y agoIn Tcl you can redefine "if", or even delete it entirely if you're crazy enough :-)
- middayc 1y agoYou can't delete word binding in Rye. I will have to add some solution just for REPL, because sometimes you instantiate something and make a bug and need to reiterate, but in the language itself no.
- middayc 1y agoI don't know a lot about Tcl, but one thing I know is said for it "everything is a string". In REBOL's it's somewaht reverse as all this live code are REBOL (Rye) values and REBOL (and Rye) have an unusual number of datatypes, REBOL 30+ (many literal types), which it uses as additional information for functions to work with, and is usefull at creating dialects For example file-path, url and email address are distinct types in REBOL where in mosta languages are just strings.
- spankalee 1y agoI wish they showed the `else` syntax, because the traditional ALGOL-style if-then-else statement doesn't look native when shoved into most function call notations, unless you have something pretty interesting around named parameters and expressions delimiters.
- middayc 1y agothere is no if { } else { } in REBOL or Rye and it wouldn't really fit. There is either function that accepts two code blocks. It can act as a typical if / else or as a ternary expression as it also returns the result of a block: print either pwd = "correct" { "Hello" } { "Locked" } This is Rebol's doc on either, Rye's works exactly the same: https://www.rebol.com/docs/words/weither.html https://www.rebol.com/docs/words/weither.html
- iamevn 1y agoSee the `either` function further down either some-condition { print "was true" } { print "was false" }
- deleted 1y ago[deleted]
- deleted 1y ago[deleted]
- analog31 1y agoInterestingly, Excel provides "if" as a function: =if(condition, value-if-true, value-if-false)
- middayc 1y agoYes, Io language is closest to that syntax probably: https://iolanguage.org/guide/guide.html#Introduction https://iolanguage.org/guide/guide.html#Introduction
- analog31 1y agoI wonder if it's more readable to non-programmers than control flow.
- danlitt 1y agoThat's because Excel is a pure functional language :-) https://www.youtube.com/watch?v=0yKf8TrLUOw https://www.youtube.com/watch?v=0yKf8TrLUOw
- lisbbb 1y agoThis discussion makes me so happy because people still care about programming languages and not just on stupid Java or whatever is making gobs of money. LISP should have a much larger following than it does, though I fully admit it has its own warts.
- deleted 1y ago[deleted]
- solomonb 1y agoGiven an algebraic data type such as: data List a = Nil | Cons a (List a) You can define its recursion principle by building a higher-order function that receives an element of your type and, for each constructor, receives a function that takes all the parameters of that constructor (with any recursive parameters replaced by `r`) and returns `r`. For `List` this becomes: foldr :: (() -> r) -> (a -> r -> r) -> List a -> r The eliminator for `Nil` can be simplified to `r` as `() -> r` is isomorphic to `r`: foldr :: r -> (a -> r -> r) -> List a -> r foldr z f Nil = z foldr z f (List a xs) = f a (foldr f z xs) For `Bool`: data Bool = True | False We get: bool :: a -> a -> Bool -> a bool p q True = q bool p q False = p Which is precisely an If statement as a function! :D
- mappum 1y agoI own the 'if' package on npm, which I wrote to be functions that can replace the if keyword, making no use of the if keyword in its definition.
- ozy 1y agoUseless unless the logical operators receive their rhs unevaluated. And that is generalized as a language feature.
- sparkie 1y agoA general language feature would be fexprs, or call-by-name (which can be combined with call-by-value using call-by-push-value). In Kernel[1] for example, where operatives are an improved fexpr. ($define! $if ($vau (condition if-true if-false) env ($cond ((eval condition env) (eval if-true env)) (#t (eval if-false env))))) $vau is similar to $lambda, except it doesn't implicitly evaluate its operands, and it implicitly receives it's caller's dynamic environment as a first class value which gets bound to env. $lambda is not actually a builtin in Kernel, but wrap is, which constructs an applicative by wrapping an operative. ($define! $lambda ($vau (args . body) env (wrap (eval (list* $vau args #ignore body) env)))) All functions have an underlying operative which can be extracted with unwrap. [1]:https://ftp.cs.wpi.edu/pub/techreports/pdf/05-07.pdf https://ftp.cs.wpi.edu/pub/techreports/pdf/05-07.pdf
- tromp 1y agoFor lambda calculus, the motto is "when everything is a function". The boolean true is the function λx.λy.x, while false is λx.λy.y. If b then x else y then simply becomes b x y. In a functional language like Haskell that is basically a typed lambda calculus with lots of syntactic sugar, we can replicate this with: type MyBool a = a -> a -> a myTrue :: MyBool a myTrue = \x y -> x myFalse :: MyBool a myFalse = \x y -> y myIf :: MyBool a -> a -> a -> a myIf b myThen myElse = b myThen myElse main = print $ myIf myTrue "true" "false"
- Y_Y 1y agoyourIf == myId
- tromp 1y agoNo instance for (Eq (MyBool a0 -> a0 -> a0 -> a0)) arising from a use of ‘==’ Undecidability of function equality aside, we could indeed define "myIf = id" instead.
- nextaccountic 1y agoThis is https://en.wikipedia.org/wiki/Church_encoding#Church_Booleans https://en.wikipedia.org/wiki/Church_encoding#Church_Boolean... But there are other encodings
- 1y ago
- motorest 1y agoI'm definitely missing some key insight because after reading the article I felt it was a strawman argument. Python already has conditional expressions, which already allow 'x if (predicate) else y'. Therefore in Python if is already equivalent to a function, and is composable. Once you realize this, and also understand that Python has logical operators that can short-circuit, all Python examples feel convoluted and required the blogger to go way out of it's way to write nonidiomatic Python. If the goal was to make a point with Python, why not write Python?
- middayc 1y agoPython was used as an example because people know Python and reader can compare it to something known. I wasn't trying to make Python look awkward. I was trying to write equivalent Python, you are very much welcome to suggest improvements to my Python examples. Other languages could be used instead of Python, for example Javascript. But I feel Python is more contained language, with clear ways to do thing (I guess I don't know them that well :) )
- motorest 1y ago> Python was used as an example because people know Python and reader can compare it to something known. I don't think you understood the point I made. My point is that Python supports conditional expressions for years. Support for conditional expressions already means that in Python indeed "if is just a function". Therefore, the whole premise of the article is null and void, and the article is thus pointless. This is evident to anyone who is familiar with Python. If you have any experience with Python and you are familiar with idiomatic Python and basic features such as list comprehension, you are already widely aware how "if is just a function". > I wasn't trying to make Python look awkward. I was trying to write equivalent Python (...) Except you didn't. You failed to even acknowledge that Python already supports "if is just a function" with basic aspects such as list comprehension. This basic aspect of Python is covered quite prominently in intros to Python, but somehow you failed to even acknowledge it exists, and proceeded to base your argument on a patently false claim.
- 1y ago
- correct_horse 1y agoJust here to point out that the actor’s name is Bob Odenkirk not Odendirk. In a statically typed language this would be an error at compile time not hacker news comment time.
- middayc 1y agoMy bad :), Gilligan typed language would resolve this at compile time. Will fix.
- andrepd 1y agoBravo, Vince.
- deleted 1y ago[deleted]
- matt123456789 1y agogcc() { curl -d '{"title": "Does this code look right?", "body": "$(cat $1)"' https://$HN_BASE/api/ask } export gcc
- deleted 1y ago[deleted]
- emoII 1y agoInteresting that this article makes no mention of eager vs lazy evaluation - isn’t a big reason that if, for etc has to be special forms in an eagerly evaluated language that their arguments need to be lazily evaluated, which of course, deviates from the rule? Also, lazy evaluation is achieved in an eagerly evaluated language as simply wrapping a block of code in a function, which makes lazy evaluation isomorphic with the contents of the article
- conradludgate 1y ago> You might wonder: “Won’t the block execute immediately when passed as an argument?” Here’s the key insight: in Rye, code blocks { ... } are values. They don’t evaluate until you explicitly tell them to.
- emoII 1y agoYou're correct, that is lazy evaluation. The entire article talks about lazy evaluation without mentioning it, which was my point
- middayc 1y agoI've been programming in REBOL for decade(s) so this is just how it worked and made sense and we never used term "lazy evaluation", so it not part of my vocabulary when explaining this. Blocks are not evaluated by default, but they are eagerly evaluated if the function that accepts it decides to do so (if, do, loop) ... I understand lazy evaluation more like something that is meant to be evaluated, but physically only gets evaluated when or if you do need the result, which I'm not sure is entirely the same.
- vanderZwan 1y agoLazy evaluation typically is a language-wide calling convention choice right? With that in mind I'm guessing the first-class block aspect of Rye might make it feel too loaded of a term to use to the author, because Rye's blocks-as-values are more flexible than just that. But maybe one mention of "this is kind of like lazy evaluation" would help.
- the_gipsy 1y agoWhen everything is an expression, like rust (I think), that's enough. Most of the control flow are used as statements, but if needed, they can be used directly as expression, and you get basically all the advantages. After seeing how effective this is, using a language that doesn't have this feature can be really annoying. On the other hand, I would like to explore "when arithmetics is just a function". I think Elm does this well: operators are just functions with two arguments that can be written as "1 + 2", the familiar way, or "(+) 1 2". Then you can compose it like "map ((+) 2)" (currying) so you get a function that adds 2 to every item of a list, and so on.
- middayc 1y agoThis is another subject but mathematical operators are and behave (for better and worse - there are also negative consequences of this consistency) like all other op-words, they just don't need . in front and correct, non-op-word is prepended by _. 12 + 23 ; is technically 12 ._+ 23 ; or not using op-word is _+ 12 23 ; or if we bind function _+ to add add: ?_+ ; we get 12 .add 23 ; and add 12 23 It has downside because op-words don't behave exactly as math expressions would, but you can use parenthesis and we have a math dialect which includes full math precedence rules. math { 12 * 2 + 23 * 3 }
- foofoo12 1y agoThe Trade-offs section doesn't list the biggest one. Secretly, all code wants to be spaghetti. You and your team have to put a conscious effort into prevent that from happening. Degrading the core of the language like this is like inoculating your homebrew with sewage and expecting it not to go wrong.
- middayc 1y agoThat is sort of like saying all visual art projects want to become "the million dollar / pixel homepage" so providing an empty canvas and full color palete will just enable people to create visual sewage because nothing stops them from doing so. I never programmed in a team, so my experience of programming is probably very different from yours. You probably want something like electric cattle fencing (if I borrow your juicy language) for your team, but if I program for my self I just want an open field of Rye I can explore :)
- diegoperini 1y agoThat analogy may not be suitable for this case because value proposition between the aesthetics vs the function is different for visual art projects compared to software. There is also the maintainability factor where most aged software (especially the closed source ones in private sector) change maintainers every few years. Old maintainers most often lose access to the source code and become unreachable after leaving their job.
- middayc 1y agoTrue, there is the "old maintainer" aspect, that differs. But what exactly does this mean in relation that what are special forms in other languages are function calls in Rye? Is the problem that you somebody could make their own control-structure-like functions? All these function calls have exactly the same evaluation rules, which is not something you can say about "special forms" in "normal" languages because special forms are exactly rules that break the regular evaluation rules. Rye already has a lot of control-structure-like functions in it's standard library and many other functions that accept blocks of code and aren't related to control-structures. Yes, a "stupid" person can write "stupid" code in Rye, but you don't need much flexibility in any language to write stupid code. I fully admit there are languages that are more suited for teams, and languages that are more suited for solo developers, for this reason. That was also my point mentioning "million pixel website" because that "art" is directionless and crowdsourced and a painter can use the same pixels or even more flexible options to create beautiful images.
- padjo 1y agoThe apply* ?thing is kinda hard to parse, would turn me off seeing lots of that in a codebase.
- middayc 1y agoI agree. This is not something you would usually use to program, at least not all three together, but as it's written it's consistent and signals exactly what it does, to someone that knows Rye conventions / rules. I can break it down for you, but yes ... it's quite specific, I was trying to apply an `if` which is not something I needed to do or would look to do so far. The point is that you can also apply all "control structure like" functions, like any other function - consistency, not that this is advised or often used. ?word is a get word. `x: inc 10` evaluates inc function, so x is 11, but `x: ?inc` returns the inc function, so x is the builtin function. apply is a function that applies a function to a block of arguments. It's usefull when you want to be creative, but it's not really used in run of the mill code. .apply (op-word of apply) takes first argument from the left. `?print .apply [ "Hello" ]` Here we needed to take second argument from the left and this is what a * modifier at the end of the op- or pipe-word does. `[ "hello" ] .apply* ?print` You asked for it :P
- 6gvONxR4sf7o 1y agoThere's more to this that I'd absolutely love to see in a language, and I can't tell if rye supports. If you want an ergonomic `if` you need its scope aspects too. Consider this example <beginning of the function> x = ... if foo: y = ... else: x = ... y = ... <rest of the function> Critical parts of the ergonomics are that a) in each branch, we have everything in scope that comes from <beginning of the function> b) in <rest of the function>, we have everything in scope that was assigned or reassigned in the executed branch I'd love a language that supports programmable stuff like if, since I'm tired of python autodiff not handling `if` and `for`. But it would really need programmable scope stuff to still allow the ergonomic "scope effects" that make `if` and `for` blocks ergonomic.
- middayc 1y agoSorry, but I don't understand the example. In Rye, as in REBOL all first level block evaluations (do, if, for, loop, ...) happend in current scope (context). Rye has first class contexts and it's one of more exciting things to me about it, but I'm not sure it's related to what you describe above. More on it here: https://ryelang.org/meet_rye/specifics/context/ https://ryelang.org/meet_rye/specifics/context/ One thing that pops out at the example above is that I wouldn't want to define a y inside if block, because after the if you have y defined or not defined at all, at least to my understanding of your code. Rye is constant by default, most things don't change and you need less veriables because it's expression based and it has left to right "flow" option. So you only make variables where you really need them, which is less common and specific, it should be obvious why you need a variable.
- 6gvONxR4sf7o 1y ago10 days later... sorry, I didn't see your comment. The example I gave had a few pieces: - x is defined prior to the if/else, and overwritten in just one branch - y is defined in both branches So in the rest of the function, we have both x and y available, regardless of which branch is taken. I just took a quick read of the context page and the context basics page, but it's still unclear to me whether you can program how scopes/contexts interact in rye. In my example, we I'd say we have a few different scopes worth mentioning, and I'm curious how programmably we can make them interact in rye: Scope 1. Right below the first x = ...: we have names available form <beginning of the function> and have x available as the ... stuff. Presumably the `foo` in `if foo` lives in this scope. Scope 2T. Right after the true branch's y, we have scope 1 plus y introduced Scope 2F. Right after the false branch's x and y, we have scope 1 plus x "pointing to" something new and y introduced. Scope 3. Below the if/else, where <rest of the function> lives. This is either scope 2T or scope 2F. x is either scope 1's x or scope 2F's x, and y is either scope 2T's y or 2F's y. In the original articles language, So the scope relationships in an if/else are a diamond DAG taking the names from before it, making them available in each branch's scopes, and then making a sorta disjoint union of the branch's names available afterwards. Could that be programmed in rye, to allow the kinds of naming ergonomics in my previous example, but with the if/else being programmable in the sense of the original article? I'm especially interested in whether we could overload it in the traditional autodiff sense. Responding to a different part of your comment about using names rarely in rye, I've found that I benefit a ton from handing out names more than most people do in functional languages, just for clarity and more self-documenting code. Like, the ide can say "`apples` is broken" instead of "error in location xyz" and I can rebuild my mental state better too when revisiting code.
- Cosi1125 1y agoIn R: > `if` = function(a, b) { print(a); print(b) } > if (2 < 5) { 6 } [1] TRUE [1] 6 (Rye also looks like a nice language, though!)
- middayc 1y agoI used R for a while to do visualizations, but I never got to it's more homoiconic side, but I saw since then that it has it. Can you also put code into { 6 }, like { print(6) }? Does this overwrite R's if or how does the scoping in R work?
- Cosi1125 1y agoThe `6` is the code, I just put the first thing that came to my mind there :D In my example, if you replace it with a more sophisticated code block, R will evaluate it and print out the result of the evaluation. Typically, you'd want to parse the unevaluated code, though: > `if` = function(a, b) { print(substitute(a)); print(substitute(b)) } > if (foo) { print("bar") } foo { print("bar") } It overwrites `if`, in the current scope, of course.
- skybrian 1y agoUsing closures or code blocks when they're unnecessary gets in the way of static analysis and (sometimes) readability. It's often better to avoid using language constructs that are more powerful than needed for the job. You can still use them when doing something more advanced.