figured out use for join!

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

figured out use for join!

Dennis Raddle
I'm starting to get the hang of certain aspects of typeclasses, particularly with Maybe and list types. For instance I needed to write a function as follows:

Ord k => k -> Map k [a] -> Maybe a

which evaluates to "Nothing" if there is no such key in the map, or Just the first element of [a] if there is such a key, or Nothing if there is such a key but [a] is null.

So I could write

import qualified Data.Map as M
import Control.Monad
import Data.Maybe

f k m = case M.lookup k m of
  Nothing -> Nothing
  Just xs -> listToMaybe xs

But the case "Nothing -> Nothing" is suspicious... seems like that's always a clue some typeclass could simplify it. Eventually I figured out

f k = join . fmap listToMaybe . M.lookup k


_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: figured out use for join!

Frerich Raabe
On 2015-11-11 22:12, Dennis Raddle wrote:
> f k m = case M.lookup k m of
>   Nothing -> Nothing
>   Just xs -> listToMaybe xs
>
> But the case "Nothing -> Nothing" is suspicious... seems like that's always
> a clue some typeclass could simplify it. Eventually I figured out
>
> f k = join . fmap listToMaybe . M.lookup k

The 'Nothing -> Nothing' thing may also be a good hint that using the Maybe
monad would be useful. Your function can also be defined as

   f k m = M.lookup k m >>= listToMaybe

--
Frerich Raabe - [hidden email]
www.froglogic.com - Multi-Platform GUI Testing
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: figured out use for join!

Marcin Mrotek
Hello,

using the Maybe monad would be useful. 

But he already is? Anyway, `(x >>= f) == join (fmap f x)`

Best regards,
Marcin Mrotek

_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: figured out use for join!

Frerich Raabe
On 2015-11-12 10:17, Marcin Mrotek wrote:
>> using the Maybe monad would be useful.
>
> But he already is?

Yes, of course, sorry for the imprecision. I meant to write 'using bind as
defined for the Maybe monad'.

--
Frerich Raabe - [hidden email]
www.froglogic.com - Multi-Platform GUI Testing
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners