Search code examples
listiorascal

how to use "IO actions" with list comprehension or mapper in Rascal?


I was wondering that IO actions (like println) would return a value of type void, and then we could use these actions in a list comprehension or as argument to the mapper function. However, when I try

rascal> import IO;
rascal> import List; 
rascal> [println(x) | x <- [1,2,3]];

I got a null pointer exception (part of the stacktrace bellow). The same occurs when I try

rascal> mapper([1,2,3], println);
1
java.lang.NullPointerException(internal error) at $root$(|main://$root$|)
java.lang.NullPointerException
    at io.usethesource.vallang.impl.fast.ListWriter.updateType(ListWriter.java:76)
    at io.usethesource.vallang.impl.fast.ListWriter.append(ListWriter.java:84)
    at org.rascalmpl.semantics.dynamic.ListComprehensionWriter.append(ListComprehensionWriter.java:38)

Surely, I was not really expecting a behaviour like mapping an IO action into a list in Haskell, though I do not understand the reason for this null pointer exception in Rascal.


Solution

  • The reason for the null pointer is that printf is a void function. In the current implementation this is implemented as a null pointer. You could use instead

    for(x <- [1,2,3]) println(x);