[Haskell-cafe] Rewrite this imperative in FP way
Yves Parès
yves.pares at gmail.com
Mon Feb 6 12:41:58 CET 2012
Okay.
But that's misleading, as normally x == y = True *iff* compare x y = EQ,
but there this is not verified, as you don't redefined
A function like "unionBy" doesn't exist, so IMHO to limit ambiguity, it
would be a good idea to use MyTuple *only *at the specific place where you
need its Eq instance instead of that of tuple (and then remove the Ord
MyTuple instance), and use regular tuples elsewhere. The following should
do the job:
map getTuple . (`union` c) . map MyTuple
2012/2/6 Haisheng Wu <freizl at gmail.com>
> The reason I redefined Eq is:
> When doing `union` over two list of MyTuple is just base on its first
> element.
> Basically it means: [(1,2), (2,2)] `union` [(1,0), (2,0), (0,0)]
> produce [(1,2), (2,2), (0,0)]
> rather than [(1,2),(2,2),(1,0),(2,0),(0,0)] by default.
>
> -Haisheng
>
>
>
> On Sun, Feb 5, 2012 at 11:37 PM, Yves Parès <yves.pares at gmail.com> wrote:
>
>> Concerning your first solution, I don't understand why you redefine Eq
>> but not Ord instance. Ord will still work by comparing the tuples and not
>> the first elements of said tuples.
>> Plus the good news is you don't have to do this: just use regular tuples
>> and use sort*By *or group*By *functions from Data.List with the 'on'
>> function from Data.Function.
>> For instance your Eq instance could have been written
>> x == y = (==) `on` (fst . getTuple)
>>
>> With regular tuples you can write "sortBy (compare `on` fst)".
>>
>>
>> Plus can you rewrite your original imperative algorithm with the right
>> variable names? You're using a 'd' array that's not been defined.
>>
>>
>> 2012/2/5 Haisheng Wu <freizl at gmail.com>
>>
>>> a = [1,1,1,1]
>>> b = [0,1,2,3]
>>> d = [0,0,0,0]
>>>
>>> for i in b:
>>> for j in c:
>>> if (i+j)<3:
>>> d[i+j] += a[i]
>>>
>>> My just work implementation in Haskell
>>> http://hpaste.org/57452
>>>
>>> Another people implementation in Haskell with Monad and it turns out
>>> complex and very imperatively.
>>> http://hpaste.org/57358
>>>
>>> Do you have any cool solution in FP way?
>>>
>>> Thanks.
>>> -Simon
>>>
>>> _______________________________________________
>>> Haskell-Cafe mailing list
>>> Haskell-Cafe at haskell.org
>>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>>
>>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120206/d5342fc2/attachment.htm>
More information about the Haskell-Cafe
mailing list