|
|
Warp wrote:
> Invisible <voi### [at] devnull> wrote:
>> sum [] = 0
>> sum (x:xs) = x + sum xs
>
> Don't you love it how complicated something like this looks in C++:
>
> template<typename Iterator>
> typename std::iterator_traits<Iterator>::value_type
> sum(Iterator begin, Iterator end)
> {
> typedef typename std::iterator_traits<Iterator>::value_type t;
> t result = t();
> while(begin != end) result += *begin++;
> return result;
> }
>
> Its advantage, though, is that it works with *any* container type
> as long as it has sequential iterators, and *any* value type, as long
> as it supports the + operator.
Mine works for *any* type that supports the + operator too. ;-)
As for other collection types... Well you could construct something in
Haskell, but curiosly nobody bothers. The general method seems to be to
write functions for transforming your collection into or out of a list,
and then using the existing list processing functions.
That used to seem like a pretty strange idea to me. Now I realise that
with function inlining + constructor specialisation + unboxing + stream
fusion + assorted other stuff, the resulting machine code is more or
less the same as if the list functions operated directly on the
collection anyway.
In a sense, a list really *is* a loop in Haskell. When you turn
something into a list, you're not so much creating a list object as
performing a loop over the data.
The big problem of course is that all list functions are inherantly
single-threaded (since linked lists are sequential access only). I hear
they're working on a new library of parallel array manipulation
functions. [Apparently some guy is even targetting it to nVidia's CUDA
architecture for his PhD thesis!] But none of that stuff actually works
yet...
--
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*
Post a reply to this message
|
|