Infinite (or lazy) sampling of a probability distribution - haskell

I would like to have a function that returns a lazy infinite list of integers following a poisson distribution, with a similar type signature to this one:
samplePoisson :: MonadRandom m -> Double -> m [Int]
where the Double argument is the lambda parameter of the poisson distribution.
I have looked into some libraries (statistics, random-fu) but none of them provide what i want.
Edit:
Yes, both libraries provide functions for generating single values that follow a distribution, which can be easily extended to generate a finite list by using replicateM.
Why do I want an infinite list? Because I don't know a priori the number of elements that must be generated.
Let me show an example.
Imagine I have a function that returns the position of the first 1 in a list.
findFirst1 :: [Int] -> Int
If I had the samplePoisson function for generating a lazy list, then I could write:
findFirst1 <$> samplePoisson 3.0
However, if I am not able to generate a lazy list, then I would have to write a new function with a type signature similar to this one (using the random-fu library):
findFirst1M :: RVar Int -> RVar Int
Hence, I lose the function findFirst1 that I originally had.
I hope I made myself clear this time.

Related

Can I attach a unique, run time determined tag to a selection of objects?

Consider type B and its subtype A, determined by a predicate P. An instance would be natural numbers for B and prime numbers for A, with some primality test as P. It is straightforward to implement a smart constructor for such A, defined as a newtype or a Tagged.
Now suppose the subtyping predicate is not completely determined at compile time. For example, let P be membership in a collection determined by IO input: the operator enters the coefficients for an integral polynomial and we obtain a predicate that verifies that a given number is a value of that polynomial at some index.
Can I make sure that each polynomial, and the values validated for it, are tagged in a fashion that makes them compatible with each other and incompatible with any other polynomial? Among the operations I am going to need is conversion between values and their indices, and I want to type safeguard them to avoid confusion.
This is how I imagine it to be:
polynomial :: [Integer] -> Polynomial unique
toValue :: Integer -> Polynomial unique -> Value unique
fromValue :: Integer -> Polynomial unique -> Maybe (Index unique)
toValue' :: Index unique -> Value unique
fromValue' :: Value unique -> Index unique
The point is to obtain these latter two total functions.
But I have no idea how to go about defining this polynomial function. Where would it get the unique type from?
To do it in an ST-like way you would need a library of functions to operate on the Value s and Polynomial s types, and then have a function with a type like this:
withPolynomial :: (forall s . Polynomial s -> Integer) -> [Integer] -> Integer
This will convert the [Integer] into a Polynomial s and pass it to the argument function. This function will then do whatever it wants, using your library of functions where appropriate. Any Value s values are guaranteed not to leak from the enclosing withPolynomial application, so they can't get mixed up. However this will also prevent you from storing polynomials and their values for use in future computations.

Using Haskell map when functions needs an intermediate result

I'm working thorough a Haskell text and have come across a question about making change. I'm given an ordered list of (denomonation, numCoins) tuples along with an amount and need to return a list of how many of each coin was used to make change. I have the following code that solves the problem:
useCoins :: (Int,Int) -> Int -> Int
useCoins (denomination, numCoins) target = min numCoins (target `div` denomination)
makeChange :: [(Int, Int)] -> Int -> [Int]
makeChange [] target = []
makeChange ((denomination, numCoins):xs) target =
let
coinsUsed = useCoins (denomination, numCoins) target
in coinsUsed : makeChange xs (target - (coinsUsed * denomination))
The problem is that this is in a chapter on higher-order functions and I'm having a hard time coming up with a way to use map as the target value is changing as it drops through the list. I'd love any help.
Thanks.
-mh
map is the wrong function to use, because as you note it only works for situations where each element can be handled independently, not when elements depend on each other.
However, makeChange is a function that is implementable with a fold. Specifically, your implementation incorporates all the feature of a left fold, but done by hand; you can instead implement your function in terms of foldl'.

Looking for a generic `bisect` function

I am looking for a bisect operation in Haskell similar to Python's bisect_left() and friends. The input would be a lower bound, an upper bound, a non-decreasing function (Ord a)=>(Int->a) which must be defined for all integers between the lower and upper bound, and a search value. The return value is the highest integer i where lower <= i <= upper and f(i) < search_term. Performance should be O(log(n)).
Hoogling for this:
(Ord a)=>(Int->a)->Int->Int->a->Int
does not yield any results.
Is there a standard, generic binary search operator in a library somewhere?
Ross Paterson's binary-search package on Hackage does what you're looking for. Specifically, see searchFromTo, which has type signature
searchFromTo :: Integral a => (a -> Bool) -> a -> a -> Maybe a
As Tikhon points out, [a] in Haskell is a linked list rather than an array. Since linked lists only support sequential access, it is not possible to get a logarithmic-time search on an [a] data structure. Instead, you should use a genuine array data structure -- see the vector library for the preferred implementation of arrays.
Dan Doel has written a family of binary search functions for the mutable vectors in the vector package: see Data.Vector.Algorithms.Search in his vector-algorithms library. In contrast to Ross Paterson's library, which provides a pure API, the API in Data.Vector.Algorithms.Search is monadic (that is, it must be run in the ST monad or the IO monad).
A function like bisect_left (assuming I read its documentation correctly) cannot really exists for lists.
This makes sense--since you don't have random access in O(1) in lists (remember that Haskell lists are linked lists, while Python uses something more like a vector), you could not really get an O(logn) binary search.
Particularly, just getting to the middle of the list takes O(n/2) (which is just O(n)) steps, so an algorithm that involved the middle of the list (like binary search) would have to be in Ω(n).
In short--binary search does not make sense on lists. If you're doing a lot of searching, you probably want a different data structure. Particularly, take a look at Data.Set which uses binary trees internally.
binary_search :: Ord a, Integral b => (b -> a) -> b -> b -> a -> b
binary_search f low hi a = go low hi
where
go low hi | low + 1 == hi = low
go low hi = go low' hi'
where
mid = (low + hi) `div` 2
(low',hi') = if f mid < a then (mid,hi) else (low, mid)
(This may have an off-by-one error.)

How to pick a random list element in a pure function?

I want to make a Haskell function that can pick out a random number from a given list.
My type signature is:
randomPick :: [a] -> a
What should I do?
Part of the definition of a "pure" function in Haskell is that it is referentially transparent, that is, interchangeable with the result of evaluating it. This implies that the result of evaluating it must be the same every time. Ergo, the function you want isn't possible, I'm afraid. To generate random numbers in Haskell, a function needs to do one of two things:
Take and return a pseudorandom number generator, e.g.:
randomPick :: RNG -> [a] -> (a, RNG)
Or use IO to access randomness from "the outside world":
randomPick :: [a] -> IO a
Both styles are provided by the module System.Random. Also, in the former case, passing the PRNG around can be abstracted out using the State monad, or perhaps a special-purpose Random monad.
What you've described can't be done in pure functional code.
Pure functional code implies that you will get the same output for the same input, every time. Since a randomizing function, by definition, gives you different output for the same input, this is impossible in pure functional code.
Unless you pass around an extra value as explained in #camccann's answer. Technically, it doesn't even have to be as advanced as an RNG, depending on your needs. You could pass around an integer, and multiply it by 10 and subtract 3 (or whatever), then take the modulo of that to find your index. Then your function remains pure, but you do directly control the randomness.
Another option is to use RandomRIO to generate a number in a range, which you can then use to select an index from the list. This will require you to enter the IO monad.
If you want to use random number generators in purely functional code but not have to explicitly pass around generator state then you can use state monad (or monad transformer) and hide the plumbing. State monads are still referentially transparent and it's safe & normal to escape a state monad. You could also use the ST monad if you want true local mutable state that is purely functional on the outside.
Here is some useful code I wrote and use sometimes:
rand :: (Random a, RandomGen g, MonadState g m) => a -> a -> m a
rand lo hi = do
r <- get
let (val, r') = randomR (lo, hi) r
put r'
return val

How to make a sequence-polymorphic zip function that works for both finite and infinite sequences?

I'm trying to write some sequence-related functions for my own edification and interest. So far, I have the following typeclasses:
class (Traversable s, Monad s) => Sequential s where
infixr 5 ~:
(~:) :: a -> s a -> s a
headEx :: s a -> a
tailEx :: s a -> s a
null :: s a -> Bool
class (Sequential s) => Finite s where
emptyS :: s a
The first of these (Sequential) is meant to represent all sequency things (including both finite and infinite sequences), while the second is for only finite sequency things.
I'm having some polymorphism-related issues in defining some typical list functions based on these. An example of these would be zip, which to my initial guess, would have a type signature of:
zip :: (Sequential s1, Sequential s2, Sequential s3) => s1 a -> s2 b -> s3 (a, b)
However, I run up against a problem - if I want to zip together an infinite sequence and a finite sequence, I obviously want the result to be a finite sequence as well. However, my attempt at an implementation fails, as Sequence has no concept of emptiness (and indeed cannot have such a concept, because infinite sequences can't be empty). Additionally, I cannot see any way of checking whether one of the Sequentials being passed in is actually a Finite, which would lead to a Finite result. As a result, I am not sure how I could write an implementation of this in its most general form.
I'm not sure whether my approach is at fault, or there's something in the language I am missing, but I would really like to know how I can implement a zip generic across finite and infinite sequences in any combination.

Resources