cocreature / lrucaching

Haskell implementation of an LRU cache
BSD 3-Clause "New" or "Revised" License
24 stars 6 forks source link

Usage #2

Closed tiredpixel closed 7 years ago

tiredpixel commented 7 years ago

Hi. Thanks for the library. :) Do you have any usage examples, however? I'm having some trouble actually integrating it, particular to do with which monad things are executing in. I'm probably making a very basic error, but it would be great if there is some project using it or documentation which could give some examples. :) I've looked at the referenced blog post, and that mentions something like a cached function wrapped over IO; is this implemented? I don't see it. Thanks! :)

cocreature commented 7 years ago

I don’t have any example at hand but let me try to explain the basic API. I’m focusing here on Data.LruCache.IO since that is probably most appropriate for most usecases.

You first create a cache using newLruHandle. I think that function should be self-explanatory but I’m happy to explain it if you have trouble understanding it.

Now you can make use of the cache you just created using cached. Each time you want to lookup a cached result if it’s available or do some expensive operation to get it you call cached lruCache key expensiveOperation. lruCache is the cache you just created. key is the key to which the cached value belongs and expensiveOperation is responsible for calculating the value corresponding key if it’s not in the cache. cached will then automatically check whether the value belonging to key is in the cache. If that’s the case it just returns it. If that’s not the cache it calls expensiveOperation, adds the result to the cache (potentially evicting other elements if the cache is full) and returns this value to you.

tiredpixel commented 7 years ago

@cocreature, thank you. That's really, really helpful. It makes sense; I was misunderstanding some things. I'll give it a try and report back. :) Thanks again—really very much appreciated! :)

cocreature commented 7 years ago

@tiredpixel If you have any specific suggestions on how to improve the docs here or even better a PR improving the docs, that would be great!

tiredpixel commented 7 years ago

@cocreature, this is brilliant; with your advice, I had my problem sorted in an hour or so. :) I hadn't realised there was the IO wrapper, and was trying to operate directly on the cache whilst in the wrong monad (heh heh :) ). I also hadn't realised there was the cached helper function. I'll hopefully submit a small doc PR soon, once I've got the rest of my LRU connections completed. Thank you very much! (And if you're in London, let me buy you a beer. :) )