|
|
|
|
|
by philh
717 days ago
|
|
I'm not familiar with that technique and don't know what's going on from that snippet. In Haskell, any time a heterogeneous list turns out to be fine, I expect to be able to model it. Often it'll look like "I'm applying a polymorphic function to every one of these list elements", and then you can either do a sum type (as discussed in the post) or an existential (which doesn't need you to list up front all the types you might use). If the function is "is negative?", it'll look something like (untested) data SomeNum = forall a. Num a => SomeNum a
isNegative :: SomeNum -> Bool
isNegative (SomeNum n) = n < 0
numbers = [SomeNum (3 :: Int), SomeNum (5.2 :: Double), SomeNum valOfUnexpectedNumericType]
anyNegative = any isNegative numbers
...but it'll often be easier to just apply the `< 0` check to every element before putting them in the list. (If you have several functions you want to apply to them all, that's when the existential trick becomes more useful.)So you can model heterogeneous lists in this case, and it's safer (because you can't put in a value that can't be compared to 0) but also less convenient. Whether that's an improvement or not will depend on the situation. |
|
It's a slightly confusing name, though; it makes me think of a difference list, which seems to be a completely unrelated data structure (basically a rope).
http://h2.jaguarpaw.co.uk/posts/demystifying-dlist/