I am beginner to Haskell Im trying to make neuron to do that I need to generate random numbers for the weights of neurones but I'm stuck at function random it provokes an infinite loop
I can't figure where the problem is, in addition when I ask in terminal when compiled take 3 random it always give me the same numbers I want it to take different random numbers each time
l = [1,0,1,1,0,0,1,0]
toDec :: [Int] -> Float
toDec [] = 0
toDec (x:xs) = fromIntegral x+2*(toDec xs)
next :: [Int] -> [Int]
next xs = xs'
where xs' = v:(init xs)
v = xor (last xs) (xs!!4)
random :: [Float]
random = ran l
where ran l = ( (toDec l) / 255.0):(ran (next l))
-- simple neuron
data Neuron = Neuron [Float]
deriving (Read,Show)
n = Neuron (take 3 random)
You function works perfectly fine: it generates an infinite list of pseudorandom numbers.
(It's not a particularly good PRNG – for serious applications you should better use a library, random-fu is very extensive – but for educational purposes it's fine.)
But well, you need to be clear what this actually means. Because random is just a value of type [Float], it of course is always the same list. You can still use it for obtaining multiple different finite lists, by splitting up the single infinite one:
n₀, n₁, n₂ :: Neuron
(n₀:n₁:n₂:_) = Neuron <$> splits 3 random
-- | #splits n l# gives a list of sublists of #l#, each of which has length #n#.
-- If the sublists are concatenated again, you get back #l#.
splits :: Int -> [a] -> [[a]]
splits nPerList l = case splitAt nPerList l of
(h,[]) -> [h]
(h,t) -> h : splits nPerList t
If you want something that behaves like the “random functions” in imperative languages, i.e. something that gives a different value each time it's called... well that's not a function then, because a function must for given input yield always the same result. However you can implement it as an action in a suitable monad. In an imperative language, there would be an implicit state of the PRNG. You can have that in Haskell too, except the state is explicit (which actually has a lot of advantages for reliability).
import Control.Monad.Trans.State
type RandSupply = State [Float]
oneRandom :: RandSupply Float
oneRandom = do
~(h:t) <- get -- This is a bit of a hack†
put t
return h
randomNeuron :: Int -> RandSupply Neuron
randomNeuron nWeights = Neuron <$> replicateM nWeights oneRandom
Then you can write code like
import Control.Monad
(`evalState`random) $ do
...
n <- randomNeuron 3
...
n₅ <- randomNeuron 5
...
and n and n₅ will have different weights, because the state of the supply-list has changed in between.
†The irrefutable match ~(h:t) means that the action can fail badly if you try to use it with only a finite supply of random numbers. Again: the proper thing to do is to use a library for random numbers, rather than rolling your own.
Related
I have a recursive Haskell function that takes a number n and generates a list that is n long of squared numbers from 1 up.
The code works but instead of the list for n=3 being [9,4,1] I want it to be [1,4,9].
sqNList :: Int -> [Int]
sqNList 0 = []
sqNList n = n*n : sqNList (n-1)
I've tried swappig the : for a ++ but then the pattern matching doesn't work. I have only just started Haskell today so may be obvious
The best approach is to implement sqNList in terms of a helper function that counts from 1 up to n. That way you can just generate the list in the correct order in the first place.
sqNList :: Int -> [Int]
sqNList n = sqNListHelper 1 n
sqNListHelper :: Int -> Int -> [Int]
sqNListHelper current end = ...
There are a wide variety of more sophisticated approaches, but this is the easiest approach to debug/test interactively that also has you figuring out how to do everything yourself.
More sophisticated approaches can include list comprehensions or composing functions like map and enumFromTo to build up the logic from simpler pieces.
The easiest approach that consumes probably the least amount of memory is to work with an accumulator: a parameter you pass and update through every recursive call.
Right now you use n as an accumulator, and decrement that, but we can decide to use an accumulator i instead that starts at 1, and keeps incrementing:
helper :: Int -> Int -> [Int]
helper i n | i > n = []
| otherwise = i*i : helper (i+1) n
Now we of course have to call it with i = 1 ourselves, which is not ideal, but we can use a where clause that scopes the helper in the sqNList:
sqNList :: Int -> [Int]
sqNList n = helper 1 n
where helper :: Int -> Int -> [Int]
helper i n | i > n = []
| otherwise = i*i : helper (i+1) n
Now we can improve this a bit. For instanc there is no need to pass n through the helper calls, since it does not change, and is defined at the top level:
sqNList :: Int -> [Int]
sqNList n = helper 1
where helper :: Int -> [Int]
helper i | i > n = []
| otherwise = i*i : helper (i+1)
There is furthermore no need to only work with Ints: we can use any type a for which Num a and Ord a:
sqNList :: (Num a, Ord a) => a -> [a]
sqNList n = helper 1
where helper i | i > n = []
| otherwise = i*i : helper (i+1)
This is a more advanced technique, so you may want to just save this for future study.
Most recursive functions tend to use one of the same general forms of recursion, so knowing which higher-order function to use saves you the effort of reimplementing (possibly incorrectly) the recursion, and lets you focus on the work that is unique to your problem.
This particular type of recursion is captured by the unfoldr function, defined in Data.List, which lets you generate a (possibly infinite) list using a generator function and an initial seed value.
Its definition can be as simple as
unfoldr f x = case f x of
Nothing -> []
Just (new, next) = new : unfoldr f next
although the actual definition is slightly more complicated for efficiency.
Essentially, you just call the generator f on the seed value x. If the result is Nothing, return an empty list. Otherwise, build a list containing a result and the list produced by a recursive call with a new seed value.
Applying this to your problem, we produce a square and the next integer as long as the input is still small enough.
import Data.List (unfoldr)
sqNList n = unfoldr generator 1
where generator x = if x > n then Nothing else Just (x*x, x+1)
So for a simple example like sqNList 3, it proceeds as follows:
Call generator 1 and get back Just (1, 2); the accumulator is now [1].
Call generator 2 and get back Just (4, 3); the accumulator is now
[1,4].
Call generator 3 and get back Just (9, 4); the accumulator is now [1,4,9].
Call generator 4 and get back Nothing. Return the accumulator [1,4,9] as the result.
Note that you generate the infinite list of all squares simply by never returning Nothing:
allSquares = unfoldr (\x -> Just (x*x, x+1)) 1
Haskell, being lazy, only generates elements in the list as you need them, so you could also define sqNList by taking only the first n items of the infinite list.
sqNList n = take n (unfoldr (\x -> Just (x*x, x+1)) 1)
Recently I am trying to figure out how to do some programming in Haskell.
I'm trying to do some simple operations. Right now I'm stuck with an operation like in this example:
input = [1,2,3,4]
output = [1,2,2,3,3,3,4,4,4,4]
That is, for each element x in input, produce x elements of x in output. So, for element 1 in input, append [1] to output. Then, for element 2 in input, append elements [2,2] to output. Then, for element 3, append [3,3,3], etc. The algorithm should work only on standard numbers.
I know it's very easy, and it's trivial to perform it in "normal" imperative programming, but as Haskell's functions are stateless, I'm having a problem in how to approach this.
Could anyone please give me some hint how can an absolute Haskell beginner cope with this?
You've just discovered monads!
Here's the general idea of what you're doing:
For each a-element in the input (which is a container-type M a, here [a]), you specify an entire new container M b. But as a final result, you want just a single "flat" container M b.
Well, let's take a look at the definition of the Monad type class:
class (Applicative m) => Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
which is exactly what you need. And lists are an instance of Monad, so you can write
replicates :: [Int] -> [Int]
replicates l = l >>= \n -> replicate n n
Alternatively, this can be written
replicates l = do
n <- l
replicate n n
It might be interesting to know that the, perhaps easier to understand, list comprehension
replicates l = [ n | n <- l, _ <- [1..n] ]
as suggested by chi, is actually just syntactic sugar for another monad expression:
[ n | n <- l, _ <- [1..n] ] ≡ l >>= \n -> [1..n] >>= \_ -> return n
... or least it used to be in some old version of GHC, I think it now uses a more optimised implementation of list comprehensions. You can still turn on that de-sugaring variant with the -XMonadComprehensions flag.
Yet another solution, exploiting list comprehensions:
output = [ n | n <- input , m <- [1..n] ]
Compare the above with the imperative Python code:
for n in input: -- n <- input
for m in range(1,n+1): -- m <- [1..n] (in Python the second extreme is excluded, hence +1)
print n -- the n in [ n | ... ]
Note that m is unused -- in Haskell it is customary to can call it _ to express this:
output = [ n | n <- input , _ <- [1..n] ]
As a beginner, I more easily understand something like this:
concat $ map (\x -> take x $ repeat x) [1,2,3,4]
For "list as monads" it is important to know that there is also "concat" operation under the hood (in bind definition), IMO
A simple solution:
rep (x:xs) = replicate x x ++ rep xs
rep [] = []
Hints:
replicate 5 "a" gives ["a","a","a","a","a"], and it works the same way for any type in the second argument, but first argument must be of type Int
the operator ++ concatenates two lists
so the inferred type of rep is [Int] -> [Int], if you need to use other types you should use conversion functions
Sometimes you need a checkered data structure, for example if you model a chess board. The simplest way to represent checkered data is via list of lists.
[[0,1,0],
[1,0,1],
[0,1,0]]
The above is the example of a checkered list. My first attempt:
import Data.List
checker :: Integral i => i -> a -> a -> [[a]]
checker n a b = genericTake n $ intersperse (genericTake n xs2) $ repeat (genericTake n xs1)
where xs1 = checker' a b
xs2 = drop 1 xs1
checker' :: a -> a -> [a]
checker' a b = intersperse b $ repeat a
The code is verbose, while the result is correct:
*Main> checker 5 0 1
[[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]]
How do i write a function to create such a list with arbitrary size in Haskell?
evenRow = 0:oddRow -- evenRow = 0:1:evenRow
oddRow = 1:evenRow
board = evenRow:oddRow:board
Here's an infinite checkered board. Saw off any rectangular part:
smallBoard = take 17 $ map (take 11) board
Parameterize this as needed.
EDIT: I haven't used cycle here for the sake of illustration. In real code you probably want it:
board = cycle [cycle [0,1], cycle [1,0]]
It's much shorter but frankly looks fairly cryptic.
I'm playing with Haskell for first time.
I've created function that returns first precise enough result. It works as expected, but I'm using generator for this. How can I replace generator in this task?
integrateWithPrecision precision =
(take 1 $ preciseIntegrals precision) !! 0
preciseIntegrals :: Double -> [Double]
preciseIntegrals precision =
[
integrate (2 ^ power) pi | power <- [0..],
enoughPowerForPrecision power precision
]
You can use the beautiful until function. Here it is:
-- | #'until' p f# yields the result of applying #f# until #p# holds.
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f x | p x = x
| otherwise = until p f (f x)
So, you can write your function like this:
integrateWithPrecision precision = integrate (2 ^ pow) pi
where
pow = until done succ 0
done pow = enoughPowerForPrecision pow precision
In your case, you do all the iteration and then compute a result just once. But until is useful even when you need to compute a result at each step - just use an (iter, result) tuple and then just extract the result at the end with snd.
It seems like you want to check higher and higher powers until you get one that satisfies a requirement. This is what you could do: First you define a function to get enough power, and then you integrate using that.
find gets the first element of a list that satisfies a condition – like being enough of a power! Then we need a fromJust to get the actual value from that. Please note that almost always, fromJust is a terrible idea to have in your code. However, in this case the list is infinite, so we will have troubles with infinite loops long before fromJust is able to crash the program.
enoughPower :: Double -> Int
enoughPower precision =
fromJust $ find (flip enoughPowerForPrecision precision) [0..]
preciseIntegrals :: Double -> Double
preciseIntegrals precision = integrate (2^(enoughPower precision)) pi
The function
\xs -> take 1 xs !! 0
is called head
head [] = error "Cannot take head of empty list"
head (x:xs) = x
Its use is somewhat unsafe, as shown it can throw an error if you pass it an empty list, but in this case since you can be certain your list is non-empty it's fine.
Also, we tend not to call these "generators" in Haskell as they're not a special form but are instead a simple consequence of lazy evaluation. In this case, preciseIntegrals is called a "list comprehension" and [0..] is nothing more than a lazily generated list.
I'm looking through a past exam paper and don't understand how to convert Int to [Int].
For example, one of the questions asks us to produce a list of all the factors of a whole number excluding both the number itself and 1.
strictFactors Int -> [Int]
strictFactors x = ???
I'm not asking for anyone to do this question for me! I just want to know how I'd convert an integer input to a list of integer output. Thanks!
Perhaps it would be easiest to have a look at some similar code. As requested, I won't give you the answer, but you should be able to use these ideas to do what you want.
Brute force
Here we're just going to use all the pairs of numbers between 1 and x to test if we can make x as the sum of two square numbers:
sumOfSquares :: Int -> [Int]
sumOfSquares x = [ (a,b) | a <- [1..x], b <- [a..x], a^2 + b^2 == x]
You call this like this:
ghci> asSumOfSquares 50
[(1,7),(5,5)]
because 50 = 1^2+7^2 and also 50 = 5^2 + 5^2.
You can think of sumOfSquares as working by first taking an a from the list [1..x] of numbers between 1 and x and then another between that and x. It then checks a^2 + b^2 == x. If that's True, it adds (a,b) to the resulting list.
Generate and check
This time let's generate some single numbers then check whether they're a multiple of another. This will calculate the least common multiple (lcm). For example, the least common multiple of 15 and 12 is 60, because it's the first number that's in both the 15 and 12 times tables.
This function isn't of the type you want but it uses all the techniques you want.
lcm :: Int -> Int -> Int
lcm x y = head [x*a | a <- [1..], (x*a) `mod` y == 0]
You can call that like this:
ghci> lcm 12 15
60
This time the list of numbers [1..] is (in principle) infinite; good job we're just picking the first one with head!
(x*a) `mod` y == 0 does the checking to see whether the number x*a is a multiple of y (mod gives the remainder after division). That's a key idea you should use.
Summary
Use a <- [1..end] to generate numbers, test them with a True/False expression (i.e. a Bool), perhaps using the mod function.
I'm quite new at Haskell but can think of a myriad ways of "converting" an Int to a list containing that same Int:
import Control.Applicative (pure)
sane_lst :: Int -> [Int]
sane_lst x = [x]
lst :: Int -> [Int]
lst x = take 1 $ repeat x
lst' :: Int -> [Int]
lst' = replicate 1
lst'' :: Int -> [Int]
lst'' = return
lst''' :: Int -> [Int]
lst''' = pure
lst'''' :: Int -> [Int]
lst'''' x = enumFromTo x x
I guess the point here is that you don't "convert" to a list, you rather "construct" the list you need. The staightforward strategy for the kind of question you posed is to find something that will give you a suitable starting list to work with based on your parameter, then filter, fold or comprehend as needed.
For example when I say:
lst x = take 1 $ repeat x
I'm first constructing an infinite list repeating the value I passed in, and then taking from it a list containing just the first element. So if you think about what kind of list you need to start with to find the solution to your problem you'll be halfway there.
If your only goal is to convert between the types (for now) then strictFactors x = [x] is the most canonical answer. This function is also called pure since [] is what's known as an Applicative and return since [] is known as a Monad.