Several times I wanted to go through the list and select elements that have some property, which also depends, say, on the next element in the list. For a simple example, I have a code that counts how many times the function f changes sign by the specified interval [a,b] . This is pretty obvious in an imperative language such as C:
for(double x=a; x<=b; x+=(ba)/n){ s*f(x)>0 ? : printf("%e %e\n",x, f(x)), s=sgn(f(x)); }
In Haskell, my first instinct was to pin the list with its tail, and then apply a filter and extract the elements using fst or something else. But that seems awkward and inefficient, so I helped him turn into a crease:
signChanges fabn = tail $ foldl (\(x:xs) y -> if (fx*fy)<0 then y:x:xs else x:xs) [a] [a,a+(ba)/n..b]
In any case, I feel that there is a βrightβ way to do this (as is often the case in Haskell) and that I do not know (or simply did not understand) what it is. Any help on how to express this in a more idiomatic or elegant way would be greatly appreciated, as were tips on how to generally find the βrightβ way to do something.
user328062
source share