
Hi,
Thanks for your reply. I've done zip'ing in those kinds of problem, also.
I think it'd be better if we can do it without zip'ing, with folding only.
With help of KwangYul Seo, I know now that short-circuiting with fold
is possible,
and I made ssfold version of findAdjacent:
-- Spencer Janssen's ssfold, from haskell-cafe
ssfold p f a0 xs = foldr (\x xs a -> if p a then a else xs (f a x)) id xs a0
findAdjacent :: [Int] -> Maybe Int
findAdjacent = snd . ssfold (uncurry const) step (False, Nothing)
where step acc@(True, _) _ = acc
step (False, last) x = (if Just x == last then True else False, Just x)
findAdjacent $ [1..10000] ++ [10000..]
==> 10000
It might be overkill for finding adjacent entry. It's better to use zip'ing.
But I think ssfold can be useful in other cases.
Any comments will be welcomed.
Regards,
Chul-Woong
2016-02-02 17:47 GMT+09:00 Theodore Lief Gannon
If you mean is there any f and z for which this can be done with only "foldr f z xs", I believe the answer is no. If you don't mind extra parts, though:
findAdjacent :: (Eq a) => [a] -> Maybe a findAdjacent xs = foldr f Nothing $ zip xs ps where ps = zipWith (==) (tail xs) xs f (x,p) next = if p then Just x else next
On Mon, Feb 1, 2016 at 11:15 PM, Chul-Woong Yang
wrote: Hi, all.
Can it be possible to do fold with short circuit and accumulator both? For example, can we find an element which is same value to adjacent one?
findAdjacent [1,2..n, n, n+1, n+2.......] => n \__very long__/
Though there can be many ways to do it, Can we do it with fold[r|l]?
I'll be happy to receive any comments.
Chul-Woong _______________________________________________ Beginners mailing list Beginners@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
_______________________________________________ Beginners mailing list Beginners@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners