[Haskell-cafe] more generic class instances?
Christopher Howard
christopher.howard at frigidcode.com
Sat Nov 2 08:13:57 UTC 2013
On 11/01/2013 11:14 PM, Nickolay Kudasov wrote:
>
> Hi Christopher,
>
> What you want is to make |b| (and |a|) depend on |f|. This can be done
> in several ways.
>
> With functional dependencies:
>
> |class (Integral a,Num b) =>PartialSum a b f | f -> a bwhere
> partialSum :: f -> a -> b
>
> instance (Integral a,Num b) =>PartialSum a b (a -> b)where
> partialSum f n = foldl (\u v -> u + f v)0 [1..n]|
>
> With type families:
>
> |class PartialSum fwhere
> type End f
> type Res f
> partialSum' :: f ->End f ->Res f
>
> instance (Integral a,Num b) =>PartialSum (a -> b)where
> type End (a ->b) = a
> type Res (a ->b) = b
> partialSum f n = foldl (\u v -> u + f v)0 [1..n]|
>
> I can’t see though what you’re trying to achieve. Could you provide
> some more use cases for that class?
>
>
Thanks for the response. I'll have to read up more on functional
dependencies and type families. Which do you think is more appropriate?
This little class is mostly just a test case for me to use in exploring
the specialization idea. Partial sums are something mentioned in my math
class. Generically, you can calculate any partial sum by adding up the
terms (a_1 + a_2 + a_3 + ... + a_n). However, when the terms are in
certain forms, you can use shortcut formulas. E.g., if the term is just
n, then you can just plug n into n*(n+1)/2.
So, the idea was to have a partialSum function that can calculate the
partial sum with any function passed to it (the long and slow way) but
can use a shortcut method when the function is of a particular form.
Say, a term of this type:
data LinearTerm f = LinearTerm f -- constructor not exported
linearTerm coefficient = LinearTerm (\x -> coefficient * x)
If my toy case is silly, I'm sure there are plenty of better examples
that could be given. For example, sorting functions that can "choose"
better algorithms depending on the type. (Say, the generic function uses
a comparison sort, but a type with a small number of possible values
would be better suited for a pigeon hole algorithm.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20131102/90d2b759/attachment.html>
More information about the Haskell-Cafe
mailing list