Skip to content

Instantly share code, notes, and snippets.

select :: IRequest req a => req a -> AsyncFetch req a
select req = AsyncFetch $ \cacheVar -> do
cache <- takeMVar cacheVar
case lookupCache req cache of
Just var -> do
putMVar cacheVar cache
pure var
Nothing -> do
var <- fetch req
putMVar cacheVar (insertCache req var cache)
newtype RequestCache req =
RequestCache (forall a. HashMap (req a) (MVar a))
emptyCache :: RequestCache req
lookupCache :: IRequest req a => req a -> RequestCache req -> Maybe (MVar a)
insertCache :: IRequest req a => req a -> MVar a -> RequestCache req -> RequestCache req
class Fetchable req where
fetch :: req a -> IO (MVar a)
type Cachable req a = (Eq (req a), Hashable (req a))
type IRequest req a = (Fetchable req, Cachable req a)
class Monad m => WithProfileInfo m where
friendsOf :: ProfileId -> m [ProfileId]
favoriteTopicsOf :: ProfileId -> m (Set Topic)
lastPostsOf :: ProfileId -> m [BlogPost]
suggestedPostsFor :: (WithProfileInfo m) => ProfileId -> m [BlogPost]
suggestedPostsFor userId = do
friendIds <- friendsOf userId
topics <- favoriteTopicsOf userId
friendsPosts <- forM friendIds $ \friendId -> do
posts <- lastPostsOf friendId
return (filter (isAbout topics) posts)
return (mostLiked 3 (concat friendsPosts))
mostLiked :: Int -> [BlogPost] -> [BlogPost]
algorithm1.suggestedPostsFor(new ProfileId(1)); // First algorithm
algorithm2.suggestedPostsFor(new ProfileId(2)); // Second algorithm
algorithm1.suggestedPostsFor(new ProfileId(1));
algorithm1.suggestedPostsFor(new ProfileId(2));
class SuggestPopularFriendPost {
private final IAccessProfileInfo profileInfo;
private final ExecutorService executor; // Where would it come from?
private Future<Iterable<ProfileId> friendsOf(ProfileId profileId) {
return executor.submit(() -> profileInfo.friendsOf(profileId));
}
// ... remaining code ...
}
template<typename T>
struct Node {
T content;
Node<T>* next;
};
public interface IAccessProfileInfo {
Future<Map<ProfileId, Iterable<ProfileId>>> friendsOf(Iterable<ProfileId> profileIds);
Future<Map<ProfileId, Set<Topic>>> favoriteTopicsOf(Iterable<ProfileId> profileIds);
Future<Map<ProfileId, Iterable<PostSummary>>> lastPostsOf(Iterable<ProfileId> profileIds);
}