by hskl · 9y ago · 0 comments
> 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.On a sidenote. I've seen code like `f (x:ys) = x : f ys` many times, for example in definitions of map or filter. It always seemed to me like we're wasting a lot of breath typing that - deconstructing the list with pattern matching, then reassembling it again, slightly changed. I feel like there's a general pattern here that could be factored out, do you know of anything like that?