Posts

Showing posts with the label haskell

Using closed type families to write functions “if type A, then X, else type Y”

I want to define a function that has a specialized implementation for some types and a general implementation for all other types, with more magic than {-# SPECIALIZE #-} or rewrite rules can get me. (Roughly, I want to switch from IORef to Ptr when possible.) Closed type families look like they might provide a solution: ...but it's unclear how, from here, to build a function special :: Specialized a , or something more or less equivalent. Closed type families seem to work on the type level, but I can't figure out how to do the appropriate thing on the data level. If I were willing to explicitly list all types I didn't want to specialize for, I could write a type class and make an instance for all the other types, but I want to write something that specializes a finite list of types and then does something else for all other types. How can I accomplish something like this? You can accomplish it with overlapping classes. Here's an example for writing nub which cho...

Self-Referential Definition Not Working in Haskell

New to Haskell, but I've run into something that's confusing to me, and I can't explain it or find any documentation. If I have the following code: Now, this code works perfectly well The issue comes if I attempt to move a point and assign it to itself = doesn't perform assignment; it equates two things. You are creating a recursive definition by saying that otherpoint and move otherpoint 5 5 are the same thing and are interchangeable. That means when you try to evaluate the call to move , it tries to evaluate otherpoint , which leads to the next call to move , etc. You can't simply "rebind" a variable in Haskell. Instead, use a different name. Let’s look at an example of a self-referential definition that does work: As chepner mentioned, an equals sign in Haskell is is not an assignment, but a definition. It has very different semantics than an equals sign in, for example, C or Java. In general, each variable in Haskell can only be given one definit...