News aggregator

wren gayle romano: On my pulling away from Haskell communities

Planet Haskell - Sun, 08/03/2014 - 8:32pm

Gershom Bazerman gave some excellent advice for activism and teaching. His focus was on teaching Haskell and advocating for Haskell, but the advice is much more widely applicable and I recommend it to anyone interested in activism, social justice, or education. The piece has garnered a good deal of support on reddit— but, some people have expressed their impression that Gershom's advice is targeting a theoretical or future problem, rather than a very concrete and very contemporary one. I gave a reply there about how this is indeed a very real issue, not a wispy one out there in the distance. However, I know that a lot of people like me —i.e., the people who bear the brunt of these problems— tend to avoid reddit because it is an unsafe place for us, and I think my point is deserving of a wider audience. So I've decided to repeat it here:

This is a very real and current problem. (Regardless of whether things are less bad in Haskell communities than in other programming communities.) I used to devote a lot of energy towards teaching folks online about the ideas behind Haskell. However, over time, I've become disinclined to do so as these issues have become more prevalent. I used to commend Haskell communities for offering a safe and welcoming space, until I stopped feeling quite so safe and welcomed myself.

I do not say this to shame anyone here. I say it as an observation about why I have found myself pulling away from the Haskell community over time. It is not a deliberate act, but it is fact all the same. The thing is, if someone like me —who supports the ideology which gave rise to Haskell, who is well-educated on the issues at hand, who uses Haskell professionally, who teaches Haskell professionally, and most importantly: who takes joy in fostering understanding and in building communities— if someone like me starts instinctively pulling away, that's a problem.

There are few specific instances where I was made to feel unsafe directly, but for years there has been a growing ambiance which lets me know that I am not welcome, that I am not seen as being part of the audience. The ambiance (or should I say miasma?) is one that pervades most computer science and programming/tech communities, and things like dogmatic activism, dragon slaying, smarter-than-thou "teaching", anti-intellectualism, hyper-intellectualism, and talking over the people asking questions, are all just examples of the overarching problem of elitism and exclusion. The problem is not that I personally do not feel as welcomed as I once did, the problem is that many people do not feel welcome. The problem is not that my experience and expertise are too valuable to lose, it's that everyone's experience and expertise is too valuable to lose. The problem is not that I can't teach people anymore, it's that people need teachers and mentors and guides. And when the tenor of conversation causes mentors and guides to pull away, causes the silencing of experience and expertise, causes the exclusion and expulsion of large swaths of people, that always has an extremely detrimental impact on the community.

Twitter Facebook Google+ Tumblr WordPress

comments
Categories: Offsite Blogs

wren gayle romano: On my pulling away from Haskell communities

Planet Haskell - Sun, 08/03/2014 - 8:30pm

Gershom Bazerman gave some excellent advice for activism and teaching. His focus was on teaching Haskell and advocating for Haskell, but the advice is much more widely applicable and I recommend it to anyone interested in activism, social justice, or education. The piece has garnered a good deal of support on reddit— but, some people have expressed their impression that Gershom's advice is targeting a theoretical or future problem, rather than a very concrete and very contemporary one. I gave a reply there about how this is indeed a very real issue, not a wispy one out there in the distance. However, I know that a lot of people like me —i.e., the people who bear the brunt of these problems— tend to avoid reddit because it is an unsafe place for us, and I think my point is deserving of a wider audience. So I've decided to repeat it here:

This is a very real and current problem. (Regardless of whether things are less bad in Haskell communities than in other programming communities.) I used to devote a lot of energy towards teaching folks online about the ideas behind Haskell. However, over time, I've become disinclined to do so as these issues have become more prevalent. I used to commend Haskell communities for offering a safe and welcoming space, until I stopped feeling quite so safe and welcomed myself.

I do not say this to shame anyone here. I say it as an observation about why I have found myself pulling away from the Haskell community over time. It is not a deliberate act, but it is fact all the same. The thing is, if someone like me —who supports the ideology which gave rise to Haskell, who is well-educated on the issues at hand, who uses Haskell professionally, who teaches Haskell professionally, and most importantly: who takes joy in fostering understanding and in building communities— if someone like me starts instinctively pulling away, that's a problem.

There are few specific instances where I was made to feel unsafe directly, but for years there has been a growing ambiance which lets me know that I am not welcome, that I am not seen as being part of the audience. The ambiance (or should I say miasma?) is one that pervades most computer science and programming/tech communities, and things like dogmatic activism, dragon slaying, smarter-than-thou "teaching", anti-intellectualism, hyper-intellectualism, and talking over the people asking questions, are all just examples of the overarching problem of elitism and exclusion. The problem is not that I personally do not feel as welcomed as I once did, the problem is that many people do not feel welcome. The problem is not that my experience and expertise are too valuable to lose, it's that everyone's experience and expertise is too valuable to lose. The problem is not that I can't teach people anymore, it's that people need teachers and mentors and guides. And when the tenor of conversation causes mentors and guides to pull away, causes the silencing of experience and expertise, causes the exclusion and expulsion of large swaths of people, that always has an extremely detrimental impact on the community.

Twitter Facebook Google+ Tumblr WordPress

comments
Categories: Offsite Blogs

"Standardising" Haskell AST for tooling

haskell-cafe - Sun, 08/03/2014 - 8:27pm
Hi all I am looking at updating HaRe for GHC 7.8.3, and I am fighting my way through the AST changes. One of the things I have had at the back of my mind for a while is to use something like Kure universes or more generally lens to provide a set of isomorphisms from the various flavours of AST into some kind of standardised internal representation, allowing easier tool manipulation. This could potentially decouple the tools from the specific compiler/analyzer, so they could work across GHC 7.6.x, GHC 7.8.x, haskell-src-exts, haste, etc.. Obviously there would be limitations to this where an advance in the language brings in new features, but a lot of useful tool work can be done that does not touch the new stuff. I don't know if anything similar is planned in either ghc-server or another toolchain. My haskell-token-utils is a first limited attempt to bring source code round tripping to a variety of backends, but a more general solution to the AST phase would help tooling in general So, is this worth d
Categories: Offsite Discussion

Thiago Negri: Code reuse considered harmful

Planet Haskell - Sun, 08/03/2014 - 3:24pm

The title is intended to call for attention. This post is about one perspective of software development in the light of my own experience in the area, it won't contain anything really revealing and is not to be taken as an absolute true for life. It's a rant. I hope you have a good time reading it, feel free to leave me any kind of feedback.

I see a bunch of people praising reuse as being the prime thing of good software development, and few talking about replaceability. There seems to be a constant seek to avoid writing code that is used only once, as if it was a really bad thing. Then we end up with software that is made of conceptual factories that create factories that create the things the software really needs, yes there are two levels of factories, or more. Is this really necessary? How much time do we save by this extreme look for reusing code?

First, let me ask and answer a simple question: why duplicated code is annoying? Well, duplicated code makes it harder to change stuff. When you have the same piece of code written multiple times in a code base and you find that it needs a change, e.g. bug fix or new feature, you will need to change it in all places. Things can get worst if you don't know all places where the code is duplicated, so you may forget to change one of these spots. The result is that duplicated code is a sign of harder maintenance and a fertile ground for further bugs to spawn. That's why we learned to hate it. We started fighting this anti-pattern with all strength we had.

Code reuse is the perfect counter to code duplication, right? Sure, it is right, if we reuse a piece of code in two places, we have no duplication between these places. So, we did it! We found the Holy Grail of code quality, no more duplicated code, yay! But something unintended happened. Remember the old saying: with great powers, comes great responsibility. People started to be obsessed with it. As soon as they learned to use the hammer of code reuse, everything turned into a nail, when it didn't work out in the first hit, they adjust the size of the hammer and hit it again with more effort.

This seek after code reuse led us to a plethora of abstractions that seems to handle every problem by reusing some code. Don't get me wrong, lots of them are useful, these are the ones that were created from observation. The problem is the ones that are created from "it's cool to abstract", or other random reason that is not true observation. We see frameworks after frameworks that try to fit every problem of the world into a single model. Developers learn to use these frameworks and suddenly find out that the framework creator is wrong and create yet another abstraction over it or creates yet another framework that tries to use a different model to solve the world.

What happens when we have a bug in one of these abstractions or we need to enhance it? Silence, for a while, then the sky turns black, you take a break, go for a walk, come back to your computer and start blaming the other developer that created the bug or that "got the abstraction wrong", because your vision was the right one. What happened? We reused code to avoid code duplication, but we are still having the same problems: code that is hard to maintain and evolve.

My guess? We missed the enemy. Code duplication is not our enemy. Maintenance problem and rigidity of code is.

My tip? Give more focus on replaceability of code instead of reuse in your talks, codes, classes, etc. Create the right abstraction to fix the problem at hand in a way that is easy to replace the underlying code when needed. Some time in the future, you will need to change it anyway. That's what agile methodologies try to teach us: embrace change. Planning for a design to be reused says: "my design will be so awesome, that I will reuse it everywhere." That's what agile says: "your design will need to change sometime, because the requirements will change, plan for the replaceability of it." People are doing things like service oriented architecture in the wrong way because they are looking for reuse of services and not for replaceability of services, they end up with a Big Web of Mud.

That's all folks. Thanks for your time.

Categories: Offsite Blogs

Is there any way to download the Haskell Wiki to read offline (PDF or Mobi)?

Haskell on Reddit - Sun, 08/03/2014 - 3:22pm

Title.

(Sorry for asking 3 questions in a row today.)

submitted by SrPeixinho
[link] [5 comments]
Categories: Incoming News

Is there any refactoring tool for Haskell?

Haskell on Reddit - Sun, 08/03/2014 - 2:47pm

Is there any refactoring tool for haskell? Things such as:

  • Cross-modules variable renaming.
  • do notation to chain of >>=
  • foo = let a=b in c to foo = c where a = b
  • less/more point-free
  • foo = \x → x to foo x = x back and forth
  • and so on
submitted by SrPeixinho
[link] [13 comments]
Categories: Incoming News

[ANN] Hayoo Relaunch

haskell-cafe - Sun, 08/03/2014 - 2:13pm
Hi Cafe, Hayoo <http://hayoo.fh-wedel.de> has been relaunched. Hayoo is a search engine for Hackage packages, which allows you to search for functions, data types and packages. It is currently work in progress. Any feedback is greatly appreciated! Hayoo uses Hunt <https://github.com/hunt-framework> for indexing and searching, which is the successor of Holumbus. Hunt is a flexible, lightweight search platform with a powerful query language and JSON API. Example search requests are: * Function names: map <http://hayoo.fh-wedel.de/?query=map> * Function signatures: (a->b)->f a->f b <http://hayoo.fh-wedel.de/?query=%28a-%3Eb%29-%3Ef+a-%3Ef+b> * Module names: Control.Loop <http://hayoo.fh-wedel.de/?query=Control.Loop> Have a look at the examples on <http://hayoo.fh-wedel.de/examples> for some advances queries. The old Hayoo and Holumbus are still online at <http://holumbus-alt.fh-wedel.de/>
Categories: Offsite Discussion

http://www.downforeveryoneorjustme.com/haskell.org

haskell-cafe - Sun, 08/03/2014 - 1:52pm
Thinks always break on the weekend, don’t they! Apologies if this is a scheduled outtake. In the meantime, there’s fortunately a Haddock mirror on http://haddocks.fpcomplete.com/fp/7.7/20131212-1/ ;-) Cheers, Tim
Categories: Offsite Discussion

Is there any way to elegantly represent this pattern in Haskell?

Haskell on Reddit - Sun, 08/03/2014 - 12:07pm

Mind the pure function below, in an imperative language:

def foo(x,y): x = f(x) if a(x) if c(x): x = g(x) else: x = h(x) x = f(x) y = f(y) if a(y) x = g(x) if b(y) return [x,y]

That function represents a style where you have to incrementally update variables. It can be avoided in most cases, but there are situations where that pattern is unavoidable - for example, writing a cooking procedure for a robot, which inherently requires a series of steps and decisions. Now, imagine we were trying to represent foo in Haskell.

foo x0 y0 = let x1 = if a x0 then f x0 else x0 in let x2 = if c x1 then g x1 else h x1 in let x3 = f x2 in let y1 = if a y0 then f y0 else y0 in let x4 = if b y1 then g x3 else x3 in [x4,y1]

That code works, but it is too complicated and error prone due to the need for manually managing the numeric tags. Notice that, after x1 is set, x0's value should never be used again, but it still can. If you accidentally use it, that will be an undetected error.

I've managed to solve this problem using the State monad:

fooSt x y = execState (do (x,y) <- get when (a x) (put (f x, y)) (x,y) <- get if c x then put (g x, y) else put (h x, y) (x,y) <- get put (f x, y) (x,y) <- get when (a y) (put (x, f y)) (x,y) <- get when (b y) (put (g x, x))) (x,y)

This way, need for tag-tracking goes away, as well as the risk of accidentally using an outdated variable. But now the code is verbose and much harder to understand, mainly due to the repetition of (x,y) <- get.

So: what is a more readable, elegant and safe way to express this pattern?

Full code for testing.

SO cross-post.

submitted by SrPeixinho
[link] [42 comments]
Categories: Incoming News

Thiago Negri: Unity3D, Bejeweled and Domain-driven design

Planet Haskell - Sun, 08/03/2014 - 11:12am

I'm working in a new game like Bejeweled. I'm happy with the freedom of code organization that Unity3D engine allows. During my first contacts with it, I thought that almost everything would be oriented to MonoBehaviour class, but this showed to be false. This class is necessary just as a glue point between any C# code and the objects of the engine. I'll report how I've started coding this game and the changes I made so far, you can watch the following video to see the current state of the game: <iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" src="http://www.youtube.com/embed/_hlOdd1MdEk" width="420"></iframe>

I started creating a GameObject for every entity that I identified in the game mechanics:

  1. Board
  2. Piece
The board contains every pieces and manages them:
public class Board : MonoBehaviour {
private GameObject[,] pieces;
void Awake() {
pieces = /* Initialize pieces */;
}
}
The piece type is defined by a MonoBehaviour that exposes an enumeration:
public class Piece : MonoBehaviour {
public PieceType Type;
}
public enum PieceType {
Circle,
Square,
Star,
Triangle,
Hexagon,
Polygon
}

After the definition of the entities participating in the game, I started to code game's logic inside these classes. It worked for a while, but some problems appeared. The same classes had lots of different responsibilities (i.e. game's rules, animations, handling input) and this made it hard to code some stuff, because I needed to maintain a mind map of all concerns to avoid breaking something. Also, during animations, the board in memory was in an inconsistent state, waiting for the end of the animation to then continue processing.

Recently I've read some stuff about Domain-driven design (DDD) and decided to apply a bit of it in this game. My first step was to separate my code domain from the others, I selected game's mechanics as my core domain: if this part is not well behaving and it's hard to maintain, I'll be in a bad spot. Then I went to create this domain classes completely separated from the rest of the game, I ignored the existence of Unity3D at this point.

I only seen a single entity for this domain: the board. It makes no sense for the piece to exist on its own, everything that involves pieces always happens inside the board. I still have a class for the piece, but it is an internal thing of the board. My design became this:


public class BoardPosition {
public readonly int Row;
public readonly int Column;
public BoardPosition(int row, int column) {
Row = row;
Column = column;
}
}

public class Board {
private Piece[,] pieces;
public Board() {
pieces = /* Initialize pieces */;
}

#region Queries
public Piece PieceAt(BoardPosition p) { /* ... */ }
#endregion

#region Events
public delegate void PieceCreatedDelegate(BoardPosition position, Piece piece);
public event PieceCreatedDelegate PieceCreated;

public delegate void PieceDestroyedDelegate(BoardPosition position);
public event PieceDestroyedDelegate PieceDestroyed;

public delegate void PieceMovedDelegate(BoardPosition from, BoardPosition to);
public event PieceMovedDelegate PieceMoved;

public delegate void PiecesSwappedDelegate(BoardPosition a, BoardPosition b);
public event PiecesSwappedDelegate PiecesSwapped;
#endregion

#region Commands
public void SwapPieces(BoardPosition a, BoardPosition b) {
...; // Swap pieces
PiecesSwapped(a, b);
}

public void StepGameState() {
...; // Destroy pieces
...; // Move pieces
...; // Create pieces

for (...) {
PieceDestroyed(...);
}
for (...) {
PieceMoved(...);
}
for (...) {
PieceCreated(...);
}
}
#endregion
}
This way, the view part of the game register itself to handle the events generated by the board and update the user interface as needed.
public class BoardView : MonoBehaviour {
private Board board;
private GameObject[,] pieces;
void Awake() {
board = new Board();
board.PieceCreated += HandlePieceCreated;
board.PieceDestroyed += HandlePieceDestroyed;
board.PieceMoved += HandlePieceMoved;
board.PiecesSwapped += HandlePiecesSwapped;
pieces = /* Initialize pieces based on 'board' */;
}

public void HandlePieceCreated(BoardPosition position, Piece piece) { /* ... */ }
public void HandlePieceDestroyed(BoardPosition position) { /* ... */ }
public void HandlePieceMoved(BoardPosition from, BoardPosition to) { /* ... */ }
public void HandlePiecesSwapped(BoardPosition a, BoardPosition b) { /* ... */ }

void Update() {
board.Step();
if (/* ... */) {
board.SwapPieces(a, b);
}
}
}

This design made it hard to sync time between the model and the view. The model calls the methods of the view to notify about changes, the view has little space left to decide when to handle each event. In my case, some events started animations that needed to hold other events from happening, i.e. there is a temporal sequencing between some events.

I changed the model to return a list of events that happened at each command, instead of calling the handler directly:


#region Events
public interface BoardEvent {}
public class PieceCreated : BoardEvent { /* ... */ }
public class PieceDestroyed : BoardEvent { /* ... */ }
public class PieceMoved : BoardEvent { /* ... */ }
public class PiecesSwapped : BoardEvent { /* ... */ }
#endregion

#region Commands
public List<BoardEvent> SwapPieces(BoardPosition a, BoardPosition b) { /* ... */ }
public List<BoardEvent> StepGameState() { /* ... */ }
#endregion
Now, the view needs to call the handlers itself, but can decide when to handle each event:
public class BoardView : MonoBehaviour {
private List<BoardEvent> events;
void Update() {
if (events.Count < 1) { events = board.StepGameState(); }
foreach (BoardEvent e in events) {
if (CanHandleNow(e)) {
Handle(e);
}
}
// ...
if (HandledEverything) { events.Clear(); }
}
}
After this, I still felt that this temporal sequencing was not clear, it was "floating in the air". I decided to put it into the model, it's part of my domain: every event has a temporal identifier:
public class Board {
private int timeCounter;
public List<BoardEvent> StepGameState() {
...; // Destroy pieces
for (...) {
events.add(new PieceDestroyed(timeCounter, ...));
}
if (eventHappened) { timeCounter++; }

...; // Move pieces
for (...) {
events.add(new PieceMoved(timeCounter, ...));
}
if (eventHappened) { timeCounter++; }

...; // Create pieces
for (...) {
events.add(new PieceCreated(timeCounter, ...));
}
if (eventHappened) { timeCounter++; }

return events;
}
}

public class BoardView : MonoBehaviour {
private int timeCounter;
private List<BoardEvent> events;
void Update() {
if (events.Count < 1) { events = board.StepGameState(); }
foreach (BoardEvent e in events) {
if (e.When() == timeCounter) Handle(e);
if (e.When() > timeCounter) {
stillHasEventsToHandle = true;
break;
}
}
if (/*handledAnimationOfAllEventsOfMyTimeCounter*/) {
// Advance time perception of view
timeCounter++;
}
if (!stillHasEventsToHandle) {
events.Clear(); // Will step game state at next frame
}
}
}
Both view and model has a temporal identifier and the sync is more evident.

The actual code is looking very similar to the listed here. The model is handling well up to now. I feel bad about one thing: the Step command of the model may leave the board in a "not-consolidated" state, as it makes a single interaction to check for matching groups to be removed from the board. The view then needs to call the Step command more than once between handling two inputs from the user. I didn't want to make a lot of interactions in a single Step to avoid putting lots of stuff in memory before anything is handled by the interface, looks like a waste to me. I miss the lazy part of Haskell.

I still have lots of stuff to add to the game's mechanics (my core domain). I'll see the problems of this design in the next days and will post news with the next changes. Critics and suggestions are welcome.

Categories: Offsite Blogs

Hackage website seems to have been down all morning.

Haskell on Reddit - Sun, 08/03/2014 - 9:22am

Anyone know what's going on and/or when it might get fixed?

submitted by dhjdhj
[link] [4 comments]
Categories: Incoming News

www.downforeveryoneorjustme.com/haskell.org

Haskell on Reddit - Sun, 08/03/2014 - 6:58am

Tried sending this mail to Haskell Cafe, but I guess it's not just the website that is down:

Thinks always break on the weekend, don’t they! Apologies if this is a scheduled outtake. In the meantime, there’s fortunately a Haddock mirror on http://haddocks.fpcomplete.com/fp/7.7/20131212-1/ ;-) submitted by SirRockALot1
[link] [18 comments]
Categories: Incoming News

Haskell Platform 2014.2.0.0 Release Candidate 4(Windows only)

haskell-cafe - Sun, 08/03/2014 - 4:00am
This is an update to the Windows RC2 candidates. These candidates fix three problems with the installation scripts. The binary build of the packages has not changed. *Fixes:* - Fix the PATH to add the location where binaries are installed with "cabal install --global" - Fix the url shortcut that is installed, to point to the platform+ghc master indices, rather than just the ghc indices - Fix where a 32-bit HP installed on a 64-bit system was going *Installers can be found here:* - HaskellPlatform-2014.2.0.0-i386-RC4-setup.exe <http://www.ozonehouse.com/mark/platform/HaskellPlatform-2014.2.0.0-i386-RC4-setup.exe> - HaskellPlatform-2014.2.0.0-x86_64-RC4-setup.exe <http://www.ozonehouse.com/mark/platform/HaskellPlatform-2014.2.0.0-x86_64-RC4-setup.exe> - Mark P.S.: You might have noticed that the server that hosted the RC files was down intermittently yesterday and today. It suffered a double (!) disk failure. It is back up with shiny new disks. P.P.S: As always, for the reason
Categories: Offsite Discussion

How I Develop with Nix

Haskell on Reddit - Sat, 08/02/2014 - 11:31pm
Categories: Incoming News

Fantasy World Haskell

Haskell on Reddit - Sat, 08/02/2014 - 11:02pm

I recently read the following post about "Fantasy World OCaml": http://chaudhuri.info/misc/fwocaml/

This blog post details changes that the author wishes were in OCaml, both syntactic differences, library differences, build system differences, and so on.

I'm curious - what do you all think would be "Fantasy World Haskell"? What are some of the Haskell warts that you wish were fixed?

I'll start this off with a few of my pet peeves that I would currently consider:

  1. Record fields with the same name and Functor-Applicative-Monad heirarchy -- both being fixed in GHC 7.10, so maybe don't quite count.

  2. Frequent occurrence of cabal hell.

  3. The String type being used pervasively through Haskell standard library.

Things are getting a lot better quickly, so certainly these things are improving (though I'm a bit skeptical that we'll see the third point fixed any time soon, sadly...) I'm sure that many of the points y'all might think of will have been rehashed elsewhere, so if you have similar links please post them!

submitted by NiftyIon
[link] [163 comments]
Categories: Incoming News

Russell O'Connor: ICFP 2014 Post-Mortem

Planet Haskell - Sat, 08/02/2014 - 9:09pm

I participated in the 2014 ICFP programming contest this year. This year’s task was to write an AI for a simplified Pac-Man game called Lambda-Man. You could write the AI in any language you wanted, as long as it complies to a specific SECD machine architecture invented for the contest. At the end of the lightening round, it was announced that the final task included writing an AI for the ghosts as well. Again, the ghost AI could be written in any language, as long as it compiles to a separate 8-bit architecture invented for the contest.

I spent the first several hours implementing my own simulator of the arcade. Eventually I realized that I would have to start working on the AI if I was going to have an entry for the 24-hour lightening division. It was at that point I realized that the provided on-line simulator was plenty adequate for my needs and I never completed my simulator.

I have some previous experience writing assembler DSLs in Haskell to handle linking. After the 2006 ICFP contest, our team wrote a fake UM-DOS shell so that we could submit our solution in UM format. This lead me to writing an article in The Monad Reader about how to write an assembler using recursive do. After that, I encountered a really elegant and simple formulation of an assembler monad on some paste site. Unfortunately, I do not recall the author, but here is how the implementation looks.

newtype Label = Label { unLabel :: Int } data ASMMonad w a = ASMMonad { runASM :: Label -> ([w],a) } instance Monad (ASMMonad w) where return a = ASMMonad $ \_ -> ([], a) x >>= y = ASMMonad (\(Label i) -> let (o0, a) = runASM x (Label i) (o1, b) = runASM (y a) (Label (i+length o0)) in (o0 ++ o1, b)) instance MonadFix (ASMMonad w) where mfix f = ASMMonad (\i -> let (o0, a) = runASM (f a) i in (o0, a)) execASM :: ASMMonad w a -> [w] execASM m = fst $ runASM m (Label 0)

Next one adds two primitive operations. The tell function is similar to the version for the writer monad. The label function returns the current index of the output stream.

tell :: [w] -> ASMMonad w () tell l = ASMMonad $ \_ -> (l,()) label :: ASMMonad w Label label = ASMMonad $ \i -> ([],i)

Lastly one makes an ASMMonadic value for each assembly instruction

data ASM = LDC Int32 -- load constant | LD Int Int -- load variable | LDF Label -- load function | ADD {- … -} deriving Show ldc x = tell [LDC x] ld x y = tell [LD x y] ldf x = tell [LDF x] add = tell [ADD] {- … -}

At the risk of jumping ahead too far, my compiler can produce linked assembly code very simply. The clause below compiles a lambda abstraction to linked SECD assembly using recursive do.

compileH env (Abs vars body) = mdo jmp end begin <- label compileH (update env vars) body rtn end <- label ldf begin

Thanks to recursive do, the first line, jmp end, refers to the end label which is bound in the second last line.

With a DSL assembler written in Haskell, I turned to creating another DSL language in Haskell to compile to this assembly language. The SECD machine is designed for Lisp compilers, so I created a little Lisp language.

data Binding a = a := Lisp a data Lisp a = Var a | Const Int32 | Cons (Lisp a) (Lisp a) | Abs [a] (Lisp a) | Rec [Binding a] (Lisp a) {- … -}

The Abs constructor builds an n-ary lambda function. The Rec constructor plays the role of letrec to build mutually recursive references. With some abuse of the Num class and OverloadedStrings, this Lisp DSL is barely tolerable to program with directly in Haskell.

Rec [ {- … -} ,"heapNew" := ["cmp"]! (Cons "cmp" 0) -- heap layout 0 = leaf | (Cons (Cons /heap is full/ /value/) (Cons /left tree/ /right tree/)) -- "cmp" @@ ["x","y"] returns true when "x" < "y" ,"heapIsFull" := ["h"]! If (Atom "h") 1 (caar "h") ,"heapInsert" := ["cmpHeap", "v"]! Rec ["cmp" := (car "cmpHeap") ,"insert" := ["heap", "v"]! -- returns (Cons /new heap is full/ /new heap/) If (Atom "heap") (Cons (Cons 1 "v") (Cons 0 0)) (Rec ["root" := cdar "heap" ,"left" := cadr "heap" ,"right" := cddr "heap" ] $ Rec ["swap" := "cmp" @@ ["v", "root"]] $ Rec ["newRoot" := If "swap" "v" "root" ,"newV" := If "swap" "root" "v" ] $ If (caar "heap" `ou` Not ("heapIsFull" @@ ["left"])) (Rec ["rec" := "insert" @@ ["left", "newV"]] $ Cons (Cons 0 "newRoot") (Cons "rec" "right")) (Rec ["rec" := "insert" @@ ["right", "newV"]] $ Cons (Cons ("heapIsFull" @@ ["rec"]) "newRoot") (Cons "left" "rec"))) ] (Cons "cmp" ("insert" @@ [cdr "cmpHeap","v"])) {- … -}

The @@ operator is infix application for the Lisp langauge and the ! operator is infix lambda abstraction for the Lisp langauge.

This Lisp language compiles to the SECD assembly and the assembly is printed out. The compiler is very simple. It does not even implement tail call optimization. There is a bit of an annoying problem with the compiler; the assembly code is structured in exactly the same way that the original Lisp is structured. In particular, lambda abstractions are compiled directly in place, and since lambda expressions are typically not executed in the location they are declared, I have to jump over the compiled code. You can see this happening in the snippet of my compiler above. I would have preferred to write

compileH env (Abs vars body) = do fun <- proc (compileH (update env vars) body) ldf fun where proc is some function that takes an ASMMonad value and sticks the assembly code “at the end” and returns a label holding the location where the assembly code got stashed. However, I could not figure out a clever and elegent way of modifing the assembly monad to support this new primitive. This is something for you to ponder.

My Lambda AI, written in my Lisp variant, is fairly simple and similar to other entries. Lambda-Man searches out the maze for the nearest edible object. It searches down each path until it hits a junction and inserts the location of the junction into a binary heap. It also inserts the junction into a binary tree of encountered junctions. If the junction is already in the binary tree, it does not insert the junction into the heap because it has already considered it. The closest junction is popped off the heap, and the search is resumed.

There is at least one bit of surprising behaviour. If there is more than one path from one junction to another, sometimes Lambda-Man ends up taking the longer path. This behaviour did not seem to be bothersome enough to warrant fixing.

This programming task has renewed my appreciation for typed languages. The Lisp language I developed is untyped, and I made several type errors programming in it. Although it is true that I did detect (all?) my errors at run-time, they were still frustrating to debug. In a typed language, when an invariant enforced by the type system is violated, you get a compile time error that, more or less, points to the code location where the invariant is violated. In an untyped language, when an invariant is violated, you get a run-time error that, more or less, points to some point in the code where missing invariant has caused a problem. While this often is enough to determine what invariant was violated, I had little idea where the code breaking the invariant was located.

With some effort I probably could have used GADTs to bring Haskell’s type checker to the Lisp DSL, but I was not confident enough I could pull that off in time.

I also needed to write some ghost AIs. The 8-bit machine that the ghosts run on is so constrained, 256 bytes of data memory; 256 code locations; 8 registers, that it seemed to make sense to write the code in raw assembly.

The first thing I tried was to make the ghosts move randomly. This meant I needed to write my own pseudo-random number generator. Wikipedia lead me to a paper on how to write long period xorshift random number generators. The examples in that paper are all for 32-bit or 64-bit machines, but I had an 8-bit architecture. I wrote a little Haskell program to find analogous random number generators for 8-bit machines. It found 6 possibilities for 32-bit state random number generator composed of four 8-bit words that satisfied the xorshift constraints described in the paper. Here is the assembly code for getting a 2 bit pseudo-random value.

mov a,[0] div a,2 xor [0],a mov a,[0] mul a,2 xor a,[0] mov [0],[1] mov [1],[2] mov [2],[3] mul [3],8 xor [3],[2] xor [3],a ; get 2 bits mov a,[3] div a,64

The random seed is held in memory locations [0] through [3]. After moving to the successive the state, this code takes 2 pseudo-random bits from memory location [3] and puts it into register a.

I did not check the quality of this random number generator beyond constructing it so that it has a period of 232-1. I expect the bit stream to appear to be quite random.

My Lambda-Man performed reasonably well against my random ghosts, so I put some effort into making my random ghosts a little smarter. I wrote a ghost AI that tried to get above Lambda-man and attack him from above. Then I made each other ghost try to attack Lambda-man from the other three directions in the same manner. The idea is to try to trap Lambda-man between two ghosts.

These smarter ghosts were quite a bit more successful against my simple Lambda-man AI. At this point I was out of contest time, so that was it for my 2014 ICFP contest submission.

Thanks to the organizers for a terrific contest problem. I am looking forward to see the final rankings.

Categories: Offsite Blogs

easy way to plot make graphs, like matplot?

Haskell on Reddit - Sat, 08/02/2014 - 8:35pm

kinda new to haskell. im thinking something like

a = [1,2,3,4,5] b = [2,4,6,8,10]

show a b

or something like that. does it exist?

submitted by thenumber1punk
[link] [7 comments]
Categories: Incoming News

typed tagless-final interpretation examples brokenwith recent ghc

haskell-cafe - Sat, 08/02/2014 - 4:28pm
Hi all, I've been reading up on typed tagless-final interpretations [1] and the accompanying examples. It seems the stuff about CPS transformations does no longer compile, probably because of stricter typing rules. I tried both ghc 7.6 and ghc 7.8, which both give a different kind of error message. It's a bit much and long to paste here though. I would really like to get the example working, but couldn't manage by only supplying type signatures. Perhaps there is some language pragma I can turn on or off to get the old behaviour back? The 2 files needed (no further libraries needed) are: - http://okmij.org/ftp/tagless-final/course/TTF.hs (working) - http://okmij.org/ftp/tagless-final/course/CPS.hs (problem) All help would be greatly appreciated. Regards, Mathijs [1] http://okmij.org/ftp/tagless-final/course/index.html
Categories: Offsite Discussion