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.

asked Sep 24, 2014 at 0:37
\$\endgroup\$

1 Answer 1

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 ]
answered Sep 24, 2014 at 1:11
\$\endgroup\$
2
  • \$\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\$ Commented Sep 24, 2014 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\$ Commented Sep 24, 2014 at 1:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.