Skip to content

Instantly share code, notes, and snippets.

@sdiehl
Created April 8, 2016 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdiehl/79345ba544eeab507e005e28a05e0afd to your computer and use it in GitHub Desktop.
Save sdiehl/79345ba544eeab507e005e28a05e0afd to your computer and use it in GitHub Desktop.
list :: [b] -> (a -> b) -> [a] -> [b]
list def f xs = case xs of
[] -> def
_ -> fmap f xs
example :: [String]
example = list ["a"] show [1,2,3]
@ezrosent
Copy link

ezrosent commented Apr 8, 2016

Not sure if this is simpler, but it avoids the pattern-match so it could be easier to generalize

import Data.Maybe (listToMaybe)

list :: [b] -> (a -> b) -> [a] -> [b]
list def f xs = maybe def (const (fmap f xs)) (listToMaybe xs)

@dmjio
Copy link

dmjio commented Apr 8, 2016

2 cents

list :: [b] -> (a -> b) -> [a] -> [b]
list def f xs = bool (f <$> xs) def (null xs)

@jstimpfle
Copy link

Are functions like null instead of pattern match always so bad?

list def f xs = if null xs then def else fmap f xs

Feels more straightforward at least.

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