Haskell Factor again

Submitted by metaperl on Thu, 02/01/2007 - 1:55pm.


map putStrLn $
map (\(a,b) -> "Index: " ++ (show b) ++ "element: " ++ a) ( zip ["a" , "b", "c"] [0..] )


{ "a" "b" "c" } dup length [ "Index: " write . "Element: " write . ] 2each


Draw your own conclusions :)

Submitted by dons on Sat, 02/17/2007 - 6:14am.

mapM_ (uncurry (printf "Index: %d element %s\n")) (zip [0..] ["a","b","c"])

Draw your own conclusions.

That you didn't know about printf? ;-)

Submitted by Cale Gibbard on Mon, 02/19/2007 - 6:33am.

I'd probably write it as the following, which at least has the same effect as the Factor code.

forM (zip [0..] ["a","b","c"]) $ \(i,v) ->
   do putStrLn $ "Index: " ++ show i
      putStrLn $ "Element: " ++ show v

The do-block has roughly the same intent as the quoted portion of the factor code. You could also write it as something like:

putStr . unlines $ ["Index: " ++ show i, "Element: " ++ show v]

depending on your preference.

The only real reason for additional verbosity in the Haskell code is the necessity of explicitly referring to parameters, rather than implicitly popping them off of the stack. The tradeoff in the Factor code is that it's less easy to see where the data are going without "running" the code in your head. This is okay with the quoted portion being small, but if it were much longer, maintaining a picture of the stack in one's head would get more difficult. You'd probably define some variables at the start of the block and use with-scope to get lexical scoping rather than doing lots of stack shuffling. This would be roughly equivalent to using a lambda.

Another difference is in safety. In the Factor version, if the quoted portion results in the consumption of more than two values from the stack, you run the risk of stack underflow (which is a runtime error). There doesn't seem to be any static checking for this. Try adding another dot at the end of the quoted segment to see what I mean. Try it again with 1 or 2 things on the stack.

In the Haskell code, the data which the action has access to are explicitly controlled. If you want the loop to depend on another parameter, the surrounding code has to be written to provide it.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.