by wyager · 9y ago · 0 comments
I think you made a typo. This doesn't do anything. If that's the case, a functional formulation would have actually made it quite obvious.
But here's a way to do it in Haskell assuming you didn't make a typo.
f i xs
| i >= len xs = i
| xs ! i == 'a' = f (i+2) xs
| otherwise = f (i+1) xs
There is almost certainly a more elegant way to write your algorithm if I understood what you were trying to do, but here's sort of a "worst case" direct translation.EDIT:
In response to your edit, a substantially more elegant functional approach looks like
map parse . filter (not . startsWith "a")
I think you ironically chose a task that functional programming is particularly better for. > map parse . filter (not . startsWith "a")
Almost! You have to skip two lines.> The goal is to skip the line after a line starting with the letter "a".
OK, so we want the following:
["x", "y", "a", "skip", "z"] -> ["x", "y", "a", "z"]
Here's a non-clever but still more elegant (and correct) way: f (x:y:zs)
| ('a':_) <- x = x : f zs
| otherwise = x : f (y : zs)
f zs = zs
I guarantee you that there are multiple zippy one-liners that do the same thing, but I'll leave it at that for now. It's already a huge improvement, and does what it purports to!What's the `<- x`for? I know some Haskell and I've never seen that syntax. And `('a':_) = x : f zs` should be enough I think. Also I'm pretty sure each line is supposed to be a string, so it should be `("a":_) = x : f zs` :)
To do this directly without guards, it'd be:
f (x@('a':_):_:zs) = x : f zs
f (x:ys) = x : f ys
f [] = []
Not obviously better, not obviously worse.