juan_gandhi: (Default)
Juan-Carlos Gandhi ([personal profile] juan_gandhi) wrote2010-01-29 08:30 pm

how to say in Haskell...


pairwise :: [a] →  [(a, a)]
pairwise [] = []
pairwise (x:y:rest) = (x,y) : pairwise rest

is there something that does it already? Could not figure out.

[identity profile] permea-kra.livejournal.com 2010-01-30 06:25 am (UTC)(link)
No, there is no standard way to do such things, i.e. there is no famous functions in base libraries that does something alike. You can build your one primitives to work with lists, however. Parser combinators library like ReadP is a good start point.

[identity profile] rinver.livejournal.com 2010-01-30 06:42 am (UTC)(link)
Наверное так. Но что если этой функции подать список из нечётного количества элементов ? :) Или нефиг ? :)

[identity profile] http://users.livejournal.com/_navi_/ 2010-01-30 07:23 am (UTC)(link)
Nothing standard comes to my. There's a problem with your code btw: pairwise is not tail-recursive and will blow up the stack.

[identity profile] nivanych.livejournal.com 2010-01-30 12:20 pm (UTC)(link)
> is there something that does it already

А какая разница, если это пишется за полминуты?

[identity profile] nivanych.livejournal.com 2010-01-30 02:06 pm (UTC)(link)
Вот так будет лучше (и паттерн полный) ->
pairwise (x:y:rest) = (x,y) : pairwise rest
pairwise _ = []

[identity profile] vyahhi.livejournal.com 2010-01-30 02:46 pm (UTC)(link)
zip xs (tail xs)
и как-нибудь взять все элементы с позиций 0,2..

полет фантазии

[identity profile] huzhepidarasa.livejournal.com 2010-01-30 04:15 pm (UTC)(link)
pairwise xs = uncurry zip $ pairmap (map snd) $ partition fst $ zip (cycle [True, False]) xs
  where pairmap f (x,y) = (f x, f y)

хотел без рекурсии и не определяя никаких вспомогательных ф-й, но не вышло

[identity profile] http://users.livejournal.com/_adept_/ 2010-01-31 10:33 pm (UTC)(link)
Как всегда, забыли unfoldr :)


splitInto n = unfoldr (chunk n)
where chunk _ [] = Nothing
chunk n lst = Just $ splitAt n lst