[Haskell-beginners] best way to code this~~

briand at aracnet.com briand at aracnet.com
Sun May 31 15:02:29 UTC 2015


On Sun, 31 May 2015 05:17:10 +0000
Alex Hammel <ahammel87 at gmail.com> wrote:

> f as alist = [ b | (a, b) <- alist, a `elem` as ]
> 
> perhaps?

perhaps.  i have no idea how that works.  but don't spoil it for me though, i'm going to go of and study it :-)

@Chaddai . this is for very small lists, so optimization in the form of sorting and binary lookup is definitely not worth the effort.


Here's what I finally wrote.  partitionMaybe is a modified version of partition from the List library.

unsure what the ~(ts, fs) syntax is though, removing the `~` doesn't seem to matter.

this seems fairly clean. i noticed that partition simply uses foldr.  it looks like select is just a helper so that partition isn't cluttered.  i'm unsure why select was broken out as a separate function instead of just being in a where clause.  possibly to be able to assign it a an explicit type signature ?  more likely it has something to do with the fact that in the library partition is declared inline.

extract :: [(String,b)] -> [String] -> ([b], [String])
extract alist l =
  let inList s = lookup (uppercase s) alist
      (l1, l2) = partitionMaybe inList l
  in
   (l1, l2)

partitionMaybe :: (a -> Maybe b) -> [a] -> ([b],[a])
partitionMaybe p xs = foldr (select p) ([],[]) xs

select :: (a -> Maybe b) -> a -> ([b], [a]) -> ([b], [a])
select p x ~(ts,fs) | isJust y = ((fromJust y):ts,fs)
                    | otherwise = (ts, x:fs)
  where
    y = p x


More information about the Beginners mailing list