I just wrote a quick Conway's Game of Life in Haskell for practice and I though that I should now animate it.
I wanted to use GLUT + OpenGL and few seconds of Googling later, I had an example up and ready to fire. The difference in the example is that it defines a function that returns some points as myPoints :: [(GLfloat,GLfloat,GLfloat)] whereas I have Coord defined as data Coord = Coord {x :: Int, y :: Int} deriving (Show, Eq). That's all nice and neat and the game seems to work in its plain form, but there are issues when I try to draw it. Namely the part when I am supposed to pass the points to the renderer:
renderPrimitive Points $ mapM_ (\(x, y, z)->vertex$Vertex3 x y z) myPoints
That's all fine if myPoints contains values of type GLfloat but renderPrimitive Points $ mapM_ (\(Coord x y)->vertex$Vertex2 x y) myCoords complains:
No instance for (VertexComponent Int)
arising from a use of `vertex'
Possible fix: add an instance declaration for (VertexComponent Int)
I tried things like fromIntegral x and adding a type signatures :: GLfloat or GLint but it always seems to complain that it can't take the type or that it can't go Int -> GLfloat/GLint.
My question is, how do I get my Coord type to play with OpenGL types? I can't find any hint on the Web and I'd rather not make Coord = Coord {x :: GLfloat, y :: GLfloat} for the simple reason that the whole lot of other code will not play nicely with GLfloats as it's all expecting Num or Int and whatnot.
Below is minimum scenario where the issue is illustrated and which I'd love to be able to compile:
module Main
where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
data Coord = Coord {x :: Int, y :: Int} deriving (Show, Eq)
someCoords = [Coord 1 1, Coord 1 2, Coord 42 7]
main = do
(progName, _) <- getArgsAndInitialize
createWindow "Please compile."
displayCallback $= display
mainLoop
display = do
clear [ColorBuffer]
renderPrimitive Points $ mapM_ (\(Coord x y) -> vertex $ Vertex2 x y) someCoords
After hunting for a longer while with another programmer in my household, we have found a snippet of code which let us make GLfloat from an int, namely fromIntegral x :: GLfloat will produce the desired result. Similarly, fromRational can be used for Float -> GLfloat.
Related
I have a 3-dimensional array U(z,y,x) and I want to perform a complex Fourier transform in z for all values of y and x. I am planning to use the FFTW library. I figured out from the FFTW manual that there is a way to perform multiple 1d transforms at once(mentioned below).
CALL dfftw_plan_many_dft(PLAN, rank, n, howmany, in, inembed, istride, idist, out, onembed, ostride, odist, FFTW_MEASURE)
I don't clearly understand what inembed and outembed means. Could you provide more insight into this as I am new to Fortran and I am not entirely sure how to use this?
EDIT1: updated the Fortran code
It's described here actually quite well:
http://www.fftw.org/fftw3_doc/Advanced-Complex-DFTs.html
inembed and outembed allow one to embed the incoming and outgoing data into a larger dataset:
Imagine that you would like to FFT the sub-matrix of in denoted by the O elements. And possibly outembed the result into the out variable's O fields.
X X X X X X X X X X X
X X X X X X O O X X X
in = X O O X X out = X O O X X X
X O O X X
X X X X X
inembed then would be [2, 1] (column-major) and outmbed [1, 1]. Then stride would take you from slice to slice / volume to volume etc. Using stride and embed you tell FFTW, how to find the O elements for each sub-data to transform and equally, where to put them in a larger dataset.
Hope this explains it. If you already now the the BLAS interface, you will find that inembed and outembed correspond to LDA, LDB of many routines. Of course BLAS routines are limited to matrices, i.e. assume 2 dimensional operations. FFTs you may of course do in as many dimensions as you like.
If you set inembed and outembed as NULL, then FFTW assumes that there are no X fields in either input our output respectively.
I am making a sudoku solving program and I have a potentialNbrsAt function that gets the numbers that could be at position x y.
Now, I am trying to get the intersect of each lists of potential numbers in a column. Something like the onlyOnePlaceForNbrInCol function bellow.
Code:
potentialNbrsAt :: Int -> Int -> Sudoku -> [Int]
potentialNbrsAt x y sudoku = intersect rowMissingNbrs $ intersect colMissingNbrs sqrMissingNbrs
where rowMissingNbrs = getMissingNbrs $ getRow y sudoku
colMissingNbrs = getMissingNbrs $ getCol x sudoku
sqrMissingNbrs = getMissingNbrs $ getSquare squareIndex sudoku
squareIndex = 3 * (y `div` 3) + (x `div` 3)
onlyOnePlaceForNbrInCol :: Int -> Int -> Sudoku -> Bool
onlyOnePlaceForNbrInCol colIndex nbr sudoku = -- What goes here? Some pointers please???
I think onlyOnePlaceForNbrInCol should, at some point, call potentialNbrsAt with each numbers from 0 to 8 as an argument for y. Telling me how to do this would greatly help.
What about [ potentialNbrsAt x y sudoku | y <- [0..8] ] ? This gives you a list of all the results for such values of y.
So you're trying to determine whether all of the numbers [0..8] fulfill a given predicate.
I'm using Haskell openGL bindings to try to make a particle generator.
I want to store information about a particle in a record where I can then pass in fields and update them when appropriate.
So a position in the record is stored as:
data Particle = Particle { pos :: Vertex2 GLfloat }
and set like this:
Particle { pos = Vertex2 1 (0::GLfloat) }
Then I pass in the particle and try to retrieve the values like so:
drawParticle :: Particle -> IO ()
drawParticle part =
(pos part) >>= \(Vertex2 x y) ->
print x
The error I get:
Couldn't match type `Vertex2' with `IO'
Expected type: IO GLfloat
Actual type: Vertex2 GLfloat
In the return type of a call of `pos'
In the first argument of `(>>=)', namely `(pos part)'
In the expression: (pos part) >>= \ (Vertex2 x y) -> print x
I'm mildly confused about the data type Vertex2 and why it has to be declared with a single GLfloat instead of two. How would I extract numbers from the data type Vertex2 GLfloat?
(that is how would I extract Vertex2 1 (0::GLfloat) to be x = 1.0, y = 0.0?
To answer your questions:
It would be possible to define Vertex2 to take two types, to allow X to have one type and Y another, e.g. data Vertex2 xtype ytype = Vertex2 xtype ytype. However, it's generally a bad idea to have two different types for X and Y so instead it's defined as: data Vertex2 sametype = Vertex2 sametype sametype to save problems.
Since you have explicitly typed the Vertex2 in your declaration for Particle, you don't need to type the expression you list. Just Particle { pos = Vertex2 1 0 } should be enough. (Or: Particle (Vertex2 1 0)).
You get the compile error because you don't need monadic bind. part has type Particle, not IO Particle, so you don't need bind to get the value out. You can write either:
drawParticle part = let Vertex2 x y = pos part in print x
or:
drawParticle part = do
let Vertex2 x y = pos part
print x
(Note the two different forms of let, depending on whether it's in a do block; this confused me when I started out.)
Preliminary remarks
I am learning Haskell.
A question that I answered some days ago gave me the inspiration for this exercise in Haskell, which gave the opportunity for experimenting with the few things that I've learned up to now, and also left me with questions :)
Problem statement
Given a rectangle A of width w and height h find the best rectangle B that fits n times within A, where best means having the smallest perimeter.
My attempt
I've started with the basic idea of generating the set of sub-rectangles of A having an area equal to div (w * h) n, and then picking the one having the smallest perimeter.
Here are the three implementations of this idea that I came up with; they're in chronological order: I got the inspiration for the third after having done the second, which I got after having done the first (OK, there's a version 0, in which I didn't use data Rectangle but just a tuple (x, y)):
Implementation 1
data Rectangle = Rectangle { width :: Integer,
height :: Integer
} deriving (Show)
subRectangles :: Rectangle -> Integer -> [ Rectangle ]
subRectangles r n = [ Rectangle x y | x <- [1..w ], y <- [1..h], x * y == (w * h) `div` n ]
where w = width r
h = height r
bestSubRectangle :: [ Rectangle ] -> Rectangle
bestSubRectangle [ r ] = r
bestSubRectangle (r:rs)
| perimeter r < perimeter bestOfRest = r
| otherwise = bestOfRest
where bestOfRest = bestSubRectangle rs
perimeter :: Rectangle -> Integer
perimeter r = (width r) + (height r)
Implementation 2
data Rectangle = Rectangle { width :: Integer,
height :: Integer
} deriving (Show)
subRectangles :: Rectangle -> Integer -> [ Rectangle ]
subRectangles r n = [ Rectangle x y | x <- [1..w ], y <- [1..h], x * y == (w * h) `div` n ]
where w = width r
h = height r
bestSubRectangle :: [ Rectangle ] -> Rectangle
bestSubRectangle xs = foldr smaller (last xs) xs
smaller :: Rectangle -> Rectangle -> Rectangle
smaller r1 r2
| perimeter r1 < perimeter r2 = r1
| otherwise = r2
perimeter :: Rectangle -> Integer
perimeter r = (width r) + (height r)
Implementation 3
import Data.List
data Rectangle = Rectangle { width :: Integer,
height :: Integer
} deriving (Show, Eq)
instance Ord Rectangle where
(Rectangle w1 h1) `compare` (Rectangle w2 h2) = (w1 + h1) `compare` (w2 + h2)
subRectangles :: Rectangle -> Integer -> [ Rectangle ]
subRectangles r n = [ Rectangle x y | x <- [1..w ], y <- [1..h], x * y == (w * h) `div` n ]
where w = width r
h = height r
bestSubRectangle :: [ Rectangle ] -> Rectangle
bestSubRectangle = head . sort
Questions
Which approach is more idiomatic?
Which approach is better in terms of performance? bestSubRectangle in Implementation 3 depends on sort, which is at best O(n lg n), while in Implementation 1, 2 bestSubRectangle requires only scanning the array returned by subRectangles, thus making it O(n). However I'm not sure if/how Haskell laziness works on bestSubRectangle = head . sort: will sort produce only the first element of the sorted array, because of head requiring only the first element (head (x:_) = x)?
In implementation 3, when making Rectangle an instance of Ord should I also define the other methods of the Ord class? Is this the right way to make Rectangle an instance of Ord?
Any further suggestion/recommendation to improve is highly welcome.
To answer your questions about Haskell (and not about the algorithm you've choosen):
I'd say your second implementation is most idiomatic.
You are right that the problem needs only a linear scan, so that sort is likely to be more expensive than needed. You are also asking the right question when asking if, due to laziness, head . sort will compute only the first element of the result of the sort. It will, but depending on how sort is implemented, that may very well rely on sorting the whole list before it can return the first element. You should assume that it does.
You can tell from the documentation for Ord that compare is sufficient. The key phrase is Minimal complete definition: either compare or <=. Many type classes have similar use patterns. You should feel free to write a minimal implementation where they do.
Some other observations about your code (again, not the algorithm):
Function calls bind tighter than operators, as in most languages - just in Haskell there are no parenthesis around the arguments. Hence you would write perimeter r = width r + height r
If you are folding over a list that must have at least one element, you can use foldr1 as in bestSubRectangle xs = foldr1 smaller xs
Your instance of Ord for Rectangle doesn't agree with the derived instance of Eq. That is, there are values which will compare as EQ but would return False for ==. In this case, I wouldn't try to bend Rectangle's general purpose instance of Ord for purposes of perimeter comparison, and instead go with the smaller predicate you wrote in the second implementation.
Seems like you are calculating too much, inductively going through posibilities of n (number of rectangles we wish to fill up our given rectangle) we should get:
n = 1 => always returns the given rectangle
n = 2 => always returns the 2 rectangles given by bisecting the given rectangle on the longest side, i.e. gives the 2 most square rectangles
n = 3 => same as 2 using 3, divide equally along longest side.
n = 4 More complicated, essentially the question comes up is it better to put the same rectangle 4 times in a row OR is is better to bisect both length and width into a 2x2 group of rectangle. For larger numbers of n it is also a question of these configuration of factors > 1
--Essentially this is a question of factoring n, dividing the length and width by the each of the factors THEN choosing the configuration where the divided length & width (i.e. the length and width of the resulting filler rectangles) are MOST SIMILAR, (most square-like). Also note it is not necessary to try all factors against all sides. The most square rectangle will be taking the larger factor against the longer side.
n = number of filler rectangles
l = longest of width or height of container rectangle
s = shortest of width or height container rectangle
h1 = height of candidate rectangle 1
w1 = width of candidate rectangle 1
d = difference of candidate dimensions
t = smallest difference in candidate height and width (initialize t to l)
b = best fit
Therefore the steps become:
1: Factor n
2: for each factor pair of n:
(l/largest factor) - (s/smaller factor) = d
if d < t:
t = d
store current best candidate rectangle
3: Return best fit remaining after all factors have been tried
Hey folks, I have the following piece of code from C++.
for (int i=0; i < nObstacles; i++)
{
int x,y;
bool bAlreadyExists;
do {
x = rand() % nGridWidth;
y = rand() % nGridHeight;
} while (HasObstacle(x, y));
SetObstacle(x, y, true);
}
I can translate it to F# directly with no problem.
let R = new System.Random()
for i=0 to nObstacles do
let mutable bGoodToGo = false;
let mutable x =0;
let mutable y = 0
while not bGoodToGo do
x <-R.Next(nWidth)
y <-R.Next(nHeight)
bGoodToGo <- IsEmptyAt x y
board.[x,y]<-Obstacle;
Of course this probably makes most of you cringe, since this is not the way F# was meant to be used. This code has some "unkosher" concepts for F#, such as do-while loops and mutable data.
But what I would be interested in seeing is a "proper" F# translation with immutable data, and some sort of do-while equivalent.
As a first step, you can take a look how to simplify the while loop inside the for loop. One option is to use Seq.initInfinite to generate a sequence that will give you any number of random X, Y coordinates. Then you can use Seq.find to find the first one that refers to an empty board field.
I also changed isEmpty to take a tuple (so that you can pass as argument to Seq.find using partial function application) and I changed some names to follow more standard F# style (you generally wouldn't use hungarian naming notation):
let isEmpty (x, y) = board.[x,y] = -1
let rnd = new System.Random()
for i = 0 to obstacleCount do
let x, y =
// Generate infinite sequence of random X Y coordinates
Seq.initInfinite (fun _ -> rnd.Next(width), rnd.Next(height))
// Find first coordinate that refers to empty field
|> Seq.find isEmpty
// We still have mutation here
board.[x,y] <- Obstacle
I think this is quite elegant functional solution. It may be a bit slower than the imperative solution, but the point is that functional style makes it easier to write & change the implementation once you learn it (You can always use imperative style as optimization).
To avoid all mutable state, you'll need to generate locations for obstacles first and then initialize the array. For example, you could recursively add new coordinates to a set until it has the required length. Then you can generate array using Array2D.init:
let rec generateObstacles obstacles =
if Set.count obstacles = obstacleCount then obstacles
else
// Try generating new coordinate and add it to the set
// (if it is already included, this doesn't do anything)
obstacles
|> Set.add (rnd.Next(width), rnd.Next(height))
|> generateObstacles
let obstacles = generateObstacles Set.empty
Array2D.init width height (fun x y ->
if obstacles.Contains(x, y) then Obstacle else Empty)
This isn't really shorter and it will be a bit slower, so I'd stick to the first solution. However, it is a nice exercise showing recursion and sets...
Here is my try:
Seq.initInfinite (fun _ -> rnd.Next(width), rnd.Next(height))
|> Seq.filter (fun (x, y) -> IsEmptyAt x y)
|> Seq.distinct
|> Seq.take nObstacles
|> Seq.iter (fun (x, y) -> board.[x,y] <- Obstacle)
You can remove the Seq.filter if the board is empty at the beginning. Like in Tomas solution, it generates an infinite sequence of positions. Then, it removes bad and duplicated positions. Finally, it updates the board with the nObstacles first elements.