Skip to content

Instantly share code, notes, and snippets.

@missingfaktor
Created September 17, 2011 08:59
Show Gist options
  • Select an option

  • Save missingfaktor/1223770 to your computer and use it in GitHub Desktop.

Select an option

Save missingfaktor/1223770 to your computer and use it in GitHub Desktop.
A simple problem solved in Haskell
import Data.Maybe
lengths :: (Int -> Bool) -> [[a]] -> [Int]
lengths pred xs = mapMaybe lengthIfLong xs
where
lengthIfLong s = let n = length s
in if pred n
then Just n
else Nothing
main =
print $ lengths (3 <) ["hello", "k", "baby"]
@missingfaktor

Copy link
Copy Markdown
Author

@md2perpe: +1. IMO it's common enough a case to deserve an inclusion in Prelude.

By the way, what do you think about this solution?

main = print $ mapMaybe (mfilter (3 <) . Just . length) ["hello", "k", "baby"]

@md2perpe

Copy link
Copy Markdown

Nice. You rewrote my last solution using already defined functions.

Thus, justIf p = mfilter p . Just.

@missingfaktor

Copy link
Copy Markdown
Author

@md2perpe: We can go one step further, and make it point-free. :-)

justIf = (. Just) . mfilter

@md2perpe

Copy link
Copy Markdown

Oh... :-D

@md2perpe

Copy link
Copy Markdown

A question about markup...

How do you get the code blocks in your comments to be syntax colored?

@missingfaktor

Copy link
Copy Markdown
Author

@md2perpe: See "syntax highlighting" section here: http://github.github.com/github-flavored-markdown/.

@md2perpe

Copy link
Copy Markdown

Ah, I recognize that. My eyes have seen it, but my brain hasn't memorized it.
Testing:

justIf = (. Just) . mfilter

Updated my earlier posts to have syntax highlightning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment