1
\$\begingroup\$

I wrote a function, doSkip.

For an N-sized list, an element at index 0 consists of the entire input. Index 1 consists of every other element, i.e. the odd elements. Then, indexes 2 to N consist of the respective index of the input.

doSkip :: [a] -> [[a]]
doSkip []            = []
doSkip [x]           = [[x]]
doSkip xxs@(_:_:[])  = [xxs]  
doSkip xxs@(_:_:xs)  = xxs : everyOther : (rest xs)
    where everyOther  = (map (\(_, y) -> y) . filter (\(x, _) -> odd x) . zip [0..]) xxs
          rest []     = []
          rest (y:ys) = [y] : rest ys 

Testing

ghci> doSkip"FOOBAR"
["FOOBAR","OBR","O","B","A","R"]
ghci> doSkip"bippy"
["bippy","ip","p","p","y"]

Please critique. I think it's a bit long, but I'm not sure how to shorten it.

\$\endgroup\$
4
\$\begingroup\$

First up, that has to be one of the most niche functions I've ever seen :) Is there a real use case? Is this homework?

The prefix do seems strange. You obviously can't call it skip, and the definition of the function is so odd to me that I can't think of another name right now, but I would recommend thinking hard about the name.

I would recommend installing hlint. It will give you suggestions on keeping code clean, and using standard functions. For instance,

map (\(_, y) -> y)

is just map snd.

rest []     = []
rest (y:ys) = [y] : rest ys 

can be written as rest = map (: []).

As for the actual code, let's break it down. First we want the entire input:

doSkip xs = xs : ???

Now we want every other element

doSkip xs = xs : everyOther xs : ???

Then we want elements 2...

doSkip xs = xs : everyOther xs : [ [x] | x <- drop 2 xs ]

Great, so all that is left is our definition of everyOther

everyOther (x:y:xs) = y : everyOther xs
everyOther _ = []

And finally base cases, just as you had them

doSkip [] = []
doSkip [x] = [[x]]
doSkip xs = xs : everyOther xs : [ [x] | x <- drop 2 xs ]
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Technically, it is homework. However, I'm not in the class - I'm taking a class taught in 2013 for my own learning. I'm not in school anymore. Also, I re-named the function in case future students try to look up the real name. Wouldn't want them to cheat. \$\endgroup\$ – Kevin Meredith Sep 24 '14 at 1:12
  • \$\begingroup\$ @KevinMeredith respect for the self-learning. I'm also taking an online course, and there just aren't enough hours in the day. \$\endgroup\$ – mjolka Sep 24 '14 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.