MaiaVictor
MaiaVictor

Reputation: 52977

What are those functional functions called?

I'm looking for a functional way to implement this:

list = [a b c d e f]
foo(list, 3) = [[a d] [b e] [c f]]

A potential solution is:

foo(list,spacing) = zip(goo(list,spacing))

Where, for example,

goo([a b c d e f],3) = [[a b c] [d e f]]

What is foo and goo usually called, so I can look for existing solutions rather than reinventing the wheel?

Notes: Rather than trying to explain with words, I've just shown examples that'll be hopefully much easier to get. Arbitrary syntax for broader understanding.

Upvotes: 2

Views: 266

Answers (3)

MisterMetaphor
MisterMetaphor

Reputation: 6008

Your goo function is drop with flipped arguments. Given that, you can implement foo almost like you say in your question:

let foo list spacing = zip list (drop spacing list)

This still doesn't exactly give the result you need though, but close:

Prelude> foo "abcdef" 3
[('a','d'),('b','e'),('c','f')]

EDIT:

Reading more carefully, your goo function is splitAt with flipped arguments. Given that, foo can be defined like this:

let foo list spacing = (uncurry zip) $ splitAt spacing list

Which is the same as:

let foo list spacing = let (left, right) = splitAt spacing list
                       in zip left right

Upvotes: 1

elaRosca
elaRosca

Reputation: 3153

I do not think there is a built-in function for that. It's easy and nice to implement.

I know you do not want the implementation, but one of the tags was Haskell so maybe you want to see this

 p :: Int -> [a] -> [[a]]
 p n xs = [  [x | (x ,y) <- ys , y `mod` n == i]  |  i <- [0 .. n - 1] ,  let ys = zip xs [0 .. ]]

That is pretty functional.

Upvotes: 1

mobyte
mobyte

Reputation: 3752

You can use partition:

(partition 3 '[a b c d e f])
=> ((a b c) (d e f))

(partition 2 '[a b c d e f])
=> ((a b) (c d) (e f))

Edit:

(apply map list (partition 3 '[a b c d e f]))
=> ((a d) (b e) (c f))

Upvotes: 3

Related Questions