Better HN
topnewbestaskshowjobs
Log inSign up

T-R

1,407 karma · joined Jun 14, 2010 (16y ago) · 438 submissions

Submissions

comment 10y ago · link · parent

I like that Data.Sequence bypasses this whole issue by just not doing anything special:

    empty
      |> ("one"  , 1)
      |> ("two"  , 2)
      |> ("three", 3)
Edit: It's interesting that, when we have things that are supposed to commute, we use infix operators that create a layout that makes it difficult to reorder them.

comment 10y ago · link · parent

Satisfying theorems is generally for the purpose of friendliness, by ensuring consistency. In this case, they had two options:

(a) be consistent as if the language had type-level literals, which resulted in nicer code in the usual case, but some unsafety on unchecked edge cases, or

(b) give more safety, but force everyone to check for the empty list even when they don't need to.

They went with (a) - it's the type of decision Haskell is (I'd argue incorrectly) criticized for not doing - people complain about having to prove things to their compiler. Of course, in hindsight, and given the language ecosystem now (and that option (b) is instead consistent with all the monad-centric libraries, etc.), (b) seems like a better choice. Which one is better could just as easily change again if empty lists became distinguished at the type-level in Prelude in the future. This is also something that would either crash, or be similarly inconsistent (just return null, causing eventual crashes instead) in any other language. It's notable, though, that the community is making effort to fix these tiny inconsistencies, rather than punting on it for backwards compatibility, as so many other ecosystems do.

comment 10y ago · link · parent

Explicit use of recursion in functional programming is widely considered to be low level and bad form, like writing all your loops with gotos in a procedural/OOP language (as was the primary argument of the Bananas, Lenses, Envelopes, and Barbed Wire paper), it's just commonly used in intro material in a "this is how you would do this by hand" fashion. For things that fall outside of that, you always have the option of monadic loops if it makes the code clearer.

comment 10y ago · link · parent

Looking at the Japanese and Korean, it seems there's some over-romanticization here.It's a little odd seeing the Japanese "nakama", the word Monkey D. Luffy constantly throws around to refer to his crew, described like it has some deep philosophy behind it. Similar goes for Korean "Sarang", which is probably the first word every Korean student learns, and the most common word said by any K-Pop star - if its usage isn't in any way distinct from the English word for "love", it shouldn't be described like some alien concept. On the other hand, Japanese "Ai" would actually be slightly distinct, since people use "Suki" for anything more casual.

comment 10y ago · link · parent

I've been working on a functional/event sourced postgresql database for the past few years. The approach in general is great, but we're currently investigating alternatives for implementation (whether going to something like datomic, or writing a DSL to generate the SQL). It's doable on postgres, particularly with recent JSON support, but SQL is just too low level, so it's a lot of work:

- Because you tend to be doing a lot of different aggregations over the same or similar data sets, the things you most want to re-use, like "group by" and "order by" clauses or a set of columns for projections or joins, happen to be the things SQL as a language doesn't give you the ability to abstract over.

- A lot of what you want to do is a fold over the event stream, followed by a map into some format, then ultimately filtering down to just the data you want. This is an easy enough query to write, but to get reasonable performance, you need to be able to adjust the evaluation time of parts of this process/materialize intermediate results: you almost never want to do an aggregation over all of history on every read, you usually want to at least do the aggregation on write, and maybe do the `map` lazily on read. In SQL, this turns out to be a significant amount of manual work/code for something that, conceptually, should basically just be a strictness annotation. What you'd really want, at the very least, are materialized views with the ability to automatically materialize on a per-row basis when dependencies change. The recent support for Upsert will make this slightly less painful, but even so, it's a lot of work, and a lot of space for bugs / stale de-normalized data.

- What you need for playback to be performant is for your database to understand which events, or parts of events, commute with each other, so it can play them back in parallel, or at least optimize the query beyond just running a volatile stored procedure in a loop. There's no way to communicate this to postgres, so you have to model this explicitly yourself - you end up having to explicitly write 'live' code (e.g., an imperative function to update an account) that needs to produce the exact same results as 'playback' code (e.g., a materializeable query that produces the state of the whole accounts table from all user-related events).

To generalize, there's just no way to tell the database what constraints you're adhering to, so it can't do any of the heavy lifting for you - either generating code or query optimizations - and it won't do anything to make sure you won't break those constraints, either. Something that does know how you're using it, on the other hand, should at least theoretically be able to do all of this work for you and a whole lot more.

comment 11y ago · link · parent

Sure, we can have a perfectly reasonable debate as to whether or not lazy-by-default is the best choice for a language. I personally like the laziness, but if Scala, or Closure, or ML, or Elm, or maybe by some act of god COBOL "wins" by taking the good parts, that's fine.

But here, we have an article trying to make some concept approachable - some math, not tied to a specific language. Maybe it's hard for most to follow, since it assumes the readers knows what a monad is. That's fair, but it'd be the same if it were Scala.

The top comment here - and a significant number of the upvoted comments here, and on every similar article - are just baseless attacks against the idea that people should learn this. Not questions or technical discussion, just attempts to ostracize the part of the community that finds it valuable. It's anti-intellectualism, plain and simple. Maybe it's the terminology, or the syntax, or because articles didn't show the lock before giving the key, but it is what it is.

- Re: Hiring - JP Morgan may be doing layoffs somewhere, but I mentioned them because they made a "Hiring Haskell Devs" post within the last week.

Edit: Seriously, go re-read that top comment, from the condescending reference down to the assertion that it's all mental masturbation. In response to a post by a knowledgeable person trying to teach something useful to people who are interested. That's the top comment. Embarrassing.

comment 11y ago · link · parent

The theory is for getting consistent/composable APIs, and trust in the code - trust that you can optimize it, parallelize it, or just that it behaves the way it's supposed to, without having to read every line of it. You don't need to think in theory to benefit from that.

While it's certainly cute that I can `gem install` a CMS, the Ruby ecosystem is infamous for its magical, non-composable, monolithic frameworks. The functional ecosystems are working toward fixing the all-too-familiar problem where you have to either start over, or hack apart some giant stateful mess anytime your exact usecase hasn't already been built as a library. It's easy to throw a nice looking house together with Lincoln Logs, but I'd take Lego instead any day.

Edit: Also, just because someone hasn't built the tallest building in your neighborhood yet doesn't mean they're not building anything. JP Morgan, Kapersky, Facebook, and IMVU are hiring Haskell devs, just off the top of my head.

comment 11y ago · link · parent

It's definitely relevant that my complaints are from a Haskell perspective (as this is a Haskell thread). If I'm working in just about any procedural/OOP language, sum types are a completely foreign concept. If I'm working in PHP, I don't expect a consistent API. If I'm working in a strict language, I don't expect to be able to abstract my data model away from how I loop over it in memory. If I'm used to anything without some support for dependent types, I just assume that an empty list, or a list with too many entries couldn't possibly be detected at compile time. The high level constructs it does have are strictly less powerful, largely as a function of not being composable/consistent and certainly not as polymorphic as the kinds of things in Foldable/Traversable, though certainly better than writing your own for-loops.

The thing is, these are practically all you do in SQL, so it's pretty frustrating that, when working with it, so much time is dedicated to dealing with these solved problems. They're the reason you can't import a "votes" or "comments" package to your database, and why being a database expert is such a niche, specialized, and lucrative position - because so much knowledge isn't captured in the language, or the compiler, or libraries (even though it quite feasibly could be), but just spread by books and blog articles. It's why building complex things on relational databases is so hard - the level you're working at is strictly limited to "what keys do I join on to get the result set I want" and "how do I make this only loop once" - it's not inherent in the relational model/relational algebra, it's strictly a problem with SQL.

To add, as a declarative query language, it's worth also comparing to things like Prolog/Datalog. Prolog certainly doesn't get you all of the things I mentioned, either (e.g., no dependent types), but it is a much higher level of abstraction - you can describe things like "this is a one-to-one relationship" at a high level. The flipside is that, to write performant queries, you need to understand the Warren Abstract Machine, but because of its consistency, that's a significantly lower barrier to entry than trying to understand a specific database's optimizer implementation, or the arbitrary decisions in the SQL spec, and the knowledge there is actually transferrable.

comment 11y ago · link · parent

SQL is incredibly low level

- Modelling Sum Types requires giving up correctness guarantees, performance, or both.

- It's not expressive enough to get performance or abstraction - I can't communicate "this is a one-to-one relationship", "this is append-only", "this is associative", or "these things commute" in anything but comments. And my co-workers need to remember to make those joins, and think about how they can use that information to hand-optimize, because the optimizer sure as hell isn't going to do it for them.

- There's no abstraction/composition of anything at lower than a full query granularity, so everything needs to be inlined and repeated everywhere - this makes conceptually small changes, like going from single- to multi-column primary keys or vice-versa, require rewriting practically every view/query.

- Some optimizer WATs are required by the spec ('where' clauses can be propagated down the AST even past another clause that does type refinement; CTEs always materialize the result set and act as optimization walls), others may be implementation dependent (At least in Postgres, "Union All", instead of acting like a simple stream concatenation, more often than not materializes the whole result set and pages it out to disk - your 0.2ms query now takes 2 seconds). SQL is "Lazy when the stars align" and optimized by "this won't break things in the trivial case" - most effort in non-trivial queries is spent trying to convince the optimizer not to hurt you on a whim. Don't get me wrong, the devs do absolutely impressive stuff with what they've got - these quirks are clearly what needs to be done to compensate for the spec, and the spec can't change for compatibility resons - but it doesn't make it easy to work with.

- Things like missing a column in a join clause (like when changing that primary key) cause significant bugs that don't actually throw an exception/type error anywhere - they just change the size of your result set. This could be completely fixed with type-level literals.

- Types are internally inconsistent, and supplied functions are pretty much ad-hoc "we thought this might be useful". Type conversions regularly involve first converting to a string or wrapping in a nested query.

- The syntax is pants-on-head ridiculous for anything non-trivial, making education difficult and maintenance tedious. (especially window functions - SELECT a, b, LAST_VALUE(b) OVER (ORDER BY c ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS x).

The problem, though, isn't just the amount of code and maintenance issues this creates - it's the sheer amount of information that everyone on your team who touches the database needs to know and not overlook just to not create subtle bugs and significant performance issues. And all this knowledge is completely non-transferrable.

SQL is so bad that standard practice is just to not do anything on the database unless you have to; eating the connection overhead, adding yet another cache, and having a layer of wrapper functions are just considered the cost of doing business, leading a lot of people to think SQL is perfectly sufficient for what it does.

comment 11y ago · link · parent

You might be interested in looking at Gabriel Gonzalez' Morte ( http://begriffs.com/posts/2015-10-16-internet-of-code.html ), which started off as a supercompiler project, but seems to be moving somewhat in that direction.

comment 11y ago · link · parent

> Though HTTP proxies are dead thanks to HTTPS

Well, they're not as broadly useful as without HTTPS, but you can still always MITM yourself to get a free transparent caching layer between the client and your end server.

comment 11y ago · link · parent

It may be worth looking into HTTP 2. While it may or may not be supported widely enough for production yet, it provides for things like "server push", which should allow you to minimize network round trips while keeping components separately cacheable (and therefore not requiring you to do gymnastics with your API to keep your cache granularity down), which should be helpful both with and without GraphQL. I would recommend, either way, though, thinking about organizing your objects around how quickly they spoil for their given cache key (usually the URL) across multiple clients, since that ultimately determines where you can hit cache and where you need to make a new request, regardless of what libraries you're using.

comment 11y ago · link · parent

It's great that GraphQL's solved some of your issues, and you've encouraged me to look into it a bit more. One thing you should worry about, though - if at any point there's any user-specific data in an HTTP response that doesn't have the user's ID in the URL (or something pointed to by the 'vary' header), it kills the idempotence of the request, whether you're using what Rails gives you or GraphQL or XML-RPC or whatever, which is pretty much the whole point of REST. It's not just REST-nazism, this completely destroys the usefulness of any cache past that point if it doesn't understand the internals of your API (as you seem to note that you've realized at the end of the article). It might make sense to just not expose the GraphQL to the client, so you can think about the idempotence of your requests from the backend, and allow yourself to keep making use of caching proxies and client-side cache.

comment 11y ago · link · parent

I'd interpret this a bit differently - levels with good design are likely to be few and far between, since good level design is a skill. Moreover, you can't really communicate "has good design" well in a title or with stats (and to the extent you can, no one can trust it), so it's actually pretty impressive that these levels can compete at all with levels that can easily market themselves through gimmicks, references, or ridiculous difficulty.

comment 11y ago · link · parent

Talk about the practical benefits you can get, and decide based off of those:

- GET requests are supposed to be idempotent so they can be transparently cached by caching proxies. Even if you won't be taking advantage of caching proxies, it makes it easier if you can use the same data and mechanisms (i.e., HTTP headers) for server-side caching (and makes it easier to pull it out onto a separate server later). This is important if it gets a bunch of traffic or requests are resource intensive.

- Thinking about endpoints as "resources" instead of as function calls discourages you having parameters with a large or infinite set of possible inhabitants, which would dilute your cache utilization. "mysite.com/multiplicationTable.html" is nicely cacheable; You can cache "mysite.com/mult?a=5&b=10" if you want to, but how likely is someone to request that same URL again before it falls out of cache? Any information that changes the response is technically a parameter, too (since it invalidates your cache) - that especially means things like session state and side effects. That doesn't necessarily mean "never have side-effecty/RPC endpoints", but you should minimize them if you want to be scalable, since every request to one pretty much has to put load on your server.

- PUT/DELETE requests are supposed to be idempotent so they can be re-issued in case of failure. I also find it encourages design with immutable/replace semantics, rather than partial update semantics, which puts you in a better position when you want to move toward distributed/eventual consistency systems (or even just for debugging), since the data's all there in the request, and likely easier to make it commutative with other requests. Some of these things might matter to you more than others, depending on what you're building.

- Using headers properly gets you nice features like content negotiation, and provides what's needed for caching to work (e.g., 'vary' header). Using the built-in stuff means you can probably use someone else's library instead of hacking out something buggy yourself.

- HATEOAS gets you fully dynamic API discoverability. Describing your links well enough to accomplish this is pretty involved, and I'm personally not really sure it's worth the benefits, at least for anything that isn't an API having arbitrary clients built for it, or otherwise being directly navigated by some unknown end user. Maybe if there were more standardization around hypertext formats.

- Proper error codes can be nice for debugging, and theoretically can let certain situations be handled automatically (e.g., 401s could direct a user to authenticate, 302s generally redirect transparently) They also communicate some intent to e.g., search engines ("pass on my SEO link juice to this new URL"). They're a bit of a harder sell for internal APIs, since they're not really as descriptive as they should be. Probably the best practical benefit would be the ability to use client- and server-side libraries with them, or to be able to categorize your errors easily to simplify your handling, without having to dig into the response body. Also nice that you can look them up on Wikipedia - you don't have to maintain documentation for your own error format.

TL;DR: sticking to HTTP as intended helps to save you from rolling your own cache invalidation and coming up with your own new names for things, which are well known to be the two hard things in Computer Science.

comment 11y ago · link · parent

To add another way to look at it (thinking of a function as a set of tuples):

With tuples (A,B), you're listing As uniquely paired with Bs

With functions (A -> B), you're listnig unique sets of (As non-uniquely paired with Bs), so each A can go to any value of B, with replacement.

comment 11y ago · link · parent

My basic strategy is that component composition gives you more leverage than memorizing individual words. Most languages have some degree of composition for vocabulary, like root-words, prefixes/suffixes, or individual chinese characters (and the radicals they're built up from) for CJK languages. Learning those root-words/components and how to put them together into compound words, or learning how to compose words into sentences by learning grammar gives you the most leverage, once you have a small base vocabulary to practice with - it doesn't just let you build more words, it also gives you bits and pieces you can look for to help you parse out meaning of things you don't know. For vocabulary, focus memorization on verbs and their conjugation - nouns and adjectives tend to be easier to look up (and not conjugated as much as verbs, and so easier to identify), and tend to be easier to infer from context if you don't know them - if you don't know a noun in conversation, you or they can usually point to it.

I also listen to music in whatever language I'm learning - I used to use it to switch my brain between languages on the way from one language class to another. For memorization, the best way really is to just write it and repeat it a dozen times, so putting a song on repeat is really useful for refreshing your memory on commonly used words, practicing pronunciation, and even occasionally picking up new words by looking up lyrics, etc. Nothing beats immersion, though, just because, on top of practice (inherently prioritized by common usage), it gives you all the extra context to infer or reinforce meaning - memorizing words or working from a textbook means you have no extra information to go off of but what's written there. If you want to get those benefits of immersion without actual immersion, find things that mimic those qualities (extra context, prioritized by common usage, repetition), like music, kids TV shows, comic books, conversation, etc.

comment 11y ago · link · parent

That's part of it. For IO/State, the idea is basically, if you wite a function that does something, you have to test it by doing that thing, so, instead, let's write recipes to do things, and then run them (recipes here just being sets of instructions - not trying to make a weird kitchen metaphor, just seemed more clear than "build computations"). Then, the code to build the recipes can be pure, and we can maybe do neat things like check recipes for equality, change up how we run them to do practice runs while taking notes, pass the recipes around and modify them, and build up libraries of not just recipes, but recipe modifications. A nice side effect is that it lends itself really well to separation of concerns/testable code - if your language is type-checked, it enforces it. If not, it's kind of optional, but there's not much reason not to keep it pure, since you're effectively doing dependency injection already. It's useful for non-side-effecty things, too - for State monads without side-effects, our "recipe" is a state machine, and it means we're being explicit about our inputs, which also makes it easy to do stuff like lookahead - changing the state and then dropping back to a previous one.

It turns out this style of recipe-building, when you get down to the minimal stuff you need for it, is really useful for any sort of computation-in-a-context (for a recipe, the result of running the recipe is the value "in" the context - you can "modify" it by adding to the recipe, same as you can "modify" a function's return value by composing it with another function). Basically, the interface says that "return" lets you put something in a context, "join" describes how you can compose contexts, and kleisli-compose says that if you have two functions that return results in a context ( a -> ctx(b) and b -> ctx(c) ), you can compose those functions by composing the resulting contexts with "join". The end result is that if you have some context, like a recipe, you can apply changes to it ("bind"). In fact, if you have no context (the Identity monad) kleisli-compose reduces to just normal function composition, and bind reduces to application.

TL;DR: separation of concerns is a really nice side-effect of what's just a really broadly applicable interface for "more complicated but still composable stuff".

comment 11y ago · link · parent

For Monad, 'join' or the kleisli arrow (>=>) might give better intuition than bind/flatMap - maybe something like "contextComposable": kleisli arrow in the Identity monad is just function composition, and for everything else, it's function composition within a context, combining contexts according to 'join'.

comment 11y ago · link · parent

Surprised no one's brought up Haskell's Debug.Trace, which effectively does this, but returning whichever value you tell it to.

comment 11y ago · link · parent

My understanding is that it's not a proper category due to the presence of Bottom - https://wiki.haskell.org/Bottom

> Bottom is a member of any type, even the trivial type () [...] If it were not, the compiler could solve the halting problem and statically determine whether any computation terminated

You can imagine function composition and identity don't work too well on things that never complete.

comment 12y ago · link · parent

That sounds fantastic. I'll give it a look

comment 12y ago · link · parent

When you say "NoSQL-Koolaid free", do you mean "focuses on Relational" or "treats the topic objectively/academically"?

comment 12y ago · link · parent

Just taking a quick glance through the table of contents, it looks like it aims to focus more on "how to think about problems in this paradigm" (as the title implies) than the more practically-oriented "let's go write fizz-buzz" approach. For example, it jumps into function composition before it even talks about how to use GHCi. It has a chapter called "Proofs", and it seems to have a chapter focusing on using lazy evaluation to trade off time and space consumption.

Glancing at the text available, it doesn't seem to make any references to other programming languages, and takes an approach of "let's build this up from the things you learned in Math class". Seems like it might be a good fit for someone with more math than programming background, or someone with enough programming experience that they want to get to the heart of what functional programming is, but a bit jaded by the usual language tutorial format.

comment 12y ago · link · parent

But that's a pretty low bar. Using just 'pure', can you mutate an argument in a function called in a conditional expression (making it unsafe to check again)? Can it matter what order a list gets processed in a call to `map` or `filter`? Preventing mutation of global variables narrows the scope of the damage, but having just that still means that if you're maintaining someone else's code, you need to double check everything for side effects, even if they'd be limited to the inputs.

comment 12y ago · link · parent

I'm not saying it isn't - it's certainly good that it's also possible to declare something as referentially transparent, but defining the keyword "pure" to imply something much less than referential transparency is still a poor choice.

Edit: To be clear, I don't really feel too strongly about it. It's still leagues ahead of many other languages - I just think that particular choice of keyword is likely to confuse things a bit.

comment 12y ago · link · parent

That still means the function can't be treated as referentially transparent (whereas a Haskell function with debug output still can be, for the most part).

Don't get me wrong, that's still somewhat useful - it tells me "this function doesn't do anything too crazy", but it doesn't tell me "it should be safe to refactor this without having to read the function bodies of the entire call graph below this point", which makes calling it "pure" seem a bit disingenuous.

12345
15