0

I checked Haskell but even there they are using mutable data types internally.

Assuming everything is immutable, is there a way to have a cache?

Edit: Assume this is a general purpose cache which is supposed to keep the result of a computation (e.g. reading from a DB)

Mahdi
  • 1,871
  • 2
  • 24
  • 41
  • 1
    http://hackage.haskell.org/package/cache – Robert Harvey Aug 03 '18 at 19:21
  • 1
    Functional languages implement state changes by keeping a history of them. Each individual history datum is immutable. So, in theory, you cache things in Haskell by simply referring to an earlier version of them. In addition, Haskell benefits from referential transparency and lazy execution. Caches might be irrelevant. – Robert Harvey Aug 03 '18 at 19:24
  • @RobertHarvey "The cache is a shared mutable HashMap implemented using STM..." – Mahdi Aug 03 '18 at 19:50
  • @RobertHarvey not always. Sometimes you need to cache some calculation but only for a certain period of time. So simply caching a function output (provided by the language) may not be sufficient. – Mahdi Aug 03 '18 at 19:51
  • 1
    This question is too broad. What do you mean by caching? Do you mean memoization or caching in general? Caching could refer to HTTP caching, buffering, page replacement, memoization, etc. Depending upon what you're trying to do there are different ways of caching in functional programming. For example, you can generate a memoized list of Fibonacci numbers as follows: `fibs = 0 : 1 : zipWith (+) fibs (tail fibs)`. – Aadit M Shah Aug 04 '18 at 05:45
  • 1
    There is no programming language that is totally immutable. You need [some way to chicken out](https://stackoverflow.com/a/50667879/1048572) for actually doing something useful, and you can use that part of the language to build a cache. – Bergi Aug 04 '18 at 20:47

1 Answers1

1

I came across this post trying to do something similar to what the OP wanted to do, though I'm using Scala. In Scala, variables and objects can be mutable, so you can always use mutable types if you want.

But if not, in Haskell you could use the State monad, combined with Data.Map to model a stateful, mutable cache with immutable data. In Scala you could use the State monad in Cats with an immutable map.

Jeff Pratt
  • 1,619
  • 1
  • 13
  • 21