Replacing do by >>= for a scotty post - haskell

post "/introduceAnIdea" $ do
command <- jsonData
json $ handle command
How would you remove the do and change it with >>= ?

post "/introduceAnIdea" $ jsonData >>= (json . handle)
I don't think that's necessarily better in this case though.

Here's how to rewrite do-notation as >>= and >>: (NB: a newline becomes ; in the c-like notation option, which I use here.)
do { a <- m; b... } = m >>= \a -> do { b... }
do { a; b... } = a >> do { b... }
do { a } = a
So this becomes:
post "/introduceAnIdea" $ do { command <- jsonData; json $ handle command}
= post "/introduceAnIdea" $ jsonData >>= \command -> do {json $ handle command}
= post "/introduceAnIdea" $ jsonData >>= \c -> json $ handle c

Related

how made token of || in alex

I'm new at Haskell and Alex.
I'm trying to make tokens of operators in Lexer.x
here is an example of my code
\<= { \s -> TLE }
\== { \s -> TEQ }
\/= { \s -> TNEQ }
\&& { \s -> TAND }
but when I wrote
\|| { \s -> TOR }
I got a parse error on this line
How I should make token for || ?
You can use string literals to prevent escaping all characters, so you can use:
"||" { \s -> TOR }

Why can't you modify closure parameters of inline methods?

I've got this section of code:
class Main {
static inline function difference(a:Int, b:Int, ?f:(Int, Int) -> Int):Int {
if (f == null) {
f = (a, b) -> a - b;
}
return f(a, b);
}
static function main() {
trace(difference(42, 37));
trace(difference(42, 37, (a, b) -> a - b));
}
}
Which, when I compile using haxe --main Main, fails with this error:
Main.hx:11: characters 15-50 : Cannot modify a closure parameter inside inline method
Main.hx:11: characters 15-50 : For function argument 'v'
If I change Main.difference to not be inline, this error doesn't come up and everything compiles fine.
Why does this error occur?
Edit: I've found out I can also assign the argument to a variable first, and then pass the variable to Main.difference, like this:
static function main() {
var f = (a, b) -> a - b;
trace(difference(42, 37, f));
}
Which works fine with Main.difference being inlined. How does assigning the function to a variable first change things though?
This is related to how inline functions are unwrapped by the compiler. Let us take a simpler variant of your code:
class HelloWorld {
static inline function difference(a:Int, b:Int, ?f:(Int, Int) -> Int):Int {
return f(a, b);
}
static function main() {
trace(difference(42, 37, (a, b) -> a - b));
}
}
When disabling optimizations, this will yield the following JavaScript:
HelloWorld.main = function() {
console.log("HelloWorld.hx:14:",(function(a,b) {
return a - b;
})(42,37));
};
So the body of difference has been incorporated into main using a JavaScript closure. My best guess for what is happnening in your exact case is something like this:
HelloWorld.main = function() {
var v = function(a,b) {
return a - b;
}
console.log("HelloWorld.hx:14:", (function(a,b) {
if (v == null) {
v = function(a, b) {
return a - b;
}
}
return v(a, b);
})(42, 37));
};
This alters the value of v, which exists outside of difference, which has been automatically placed there as a binding for the anonymous lambda. This is what the compiler is trying to avoid. This would not be the end of the world in your case, but in general this is bad and would lead to issues in many programs.
There is a way to inline this code perfectly by hand without this, but I think that there is some weirdness surrounding how annonymous lambdas are currently handled. The situation may improve in the future.
When you explicitly defined f in main, the compiler is intelligent enough to rename the nested f as f1, which is why the issue does not occur:
HelloWorld.main = function() {
var f = function(a,b) {
return a - b;
};
var f1 = f;
if(f1 == null) {
f1 = function(a,b) {
return a - b;
};
}
console.log("HelloWorld.hx:14:",f1(42,37));
};
But this would also work if the inline part of this function is important to you:
class HelloWorld {
static inline function difference(a:Int, b:Int, ?f:(Int, Int) -> Int):Int {
var h = f;
if (h == null) {
h = (a, b) -> a - b;
}
return h(a, b);
}
static function main() {
trace(difference(42, 37, (a, b) -> a - b));
}
}

Free monad interpreter with side effect only

I need to write free monad interpreter which only perform effectfull actions but does not return any result. For free applicative I used interpreter with MyAction ~> Const[Unit, ?] signature and called it using foldMap function. However Const does not have monad instance. Id does not suit because it requires to return actual value (evaluate embedded language). Should I write my own monad instance, similar to Id but without underlying value or there is a more convient way to create interpreter which does not produce any values?
What do you mean by "not producing any value"? Here is Free monad example with interpreters that return nothing, but do something.
import cats.{Id, ~>}
import cats.effect.{ExitCode, IO, IOApp}
import cats.free.Free
import cats.free.Free.liftF
object Main extends IOApp {
// define algebra
sealed trait LaunchMissilesA[A]
case class LaunchMissileType1(arg: Int) extends LaunchMissilesA[Unit]
case class LaunchMissileType2(arg: String) extends LaunchMissilesA[Unit]
// define Free type
type LaunchMissiles[A] = Free[LaunchMissilesA, A]
// smart constructors
def launchMissileType1(arg: Int): LaunchMissiles[Unit] = liftF[LaunchMissilesA, Unit](LaunchMissileType1(arg))
def launchMissileType2(arg: String): LaunchMissiles[Unit] = liftF[LaunchMissilesA, Unit](LaunchMissileType2(arg))
// final program
def launchVariousMissiles: LaunchMissiles[Unit] =
for {
_ <- launchMissileType1(1)
_ <- launchMissileType2("str2")
} yield ()
// interpreter #1: IO
def ioMissileLauncher: LaunchMissilesA ~> IO = new (LaunchMissilesA ~> IO) {
override def apply[A](fa: LaunchMissilesA[A]): IO[A] = fa match {
case LaunchMissileType1(arg) =>
IO(println(s"[IO] launching Int missile of type 1: $arg").asInstanceOf[A])
case LaunchMissileType2(arg) =>
IO(println(s"[IO] launching String missile of type 2: $arg").asInstanceOf[A])
}
}
// interpreter #2: Id
def idMissileLauncher: LaunchMissilesA ~> Id = new (LaunchMissilesA ~> Id) {
override def apply[A](fa: LaunchMissilesA[A]): Id[A] = fa match {
case LaunchMissileType1(arg) =>
println(s"[Id] launching Int missile of type 1: $arg").asInstanceOf[A]
case LaunchMissileType2(arg) =>
println(s"[Id] launching String missile of type 2: $arg").asInstanceOf[A]
}
}
// end of the world
override def run(args: List[String]): IO[ExitCode] = for {
_ <- launchVariousMissiles.foldMap(ioMissileLauncher)
_ <- IO(launchVariousMissiles.foldMap(idMissileLauncher))
} yield ExitCode(0)
}

SequenceType of functions

I have a swift implementation of the haskell <*> operator that seems to work as long as the arguments are arrays:
public func <*> <T, U>(left:[(T)->U], right:[T]) -> [U] {
return flatten(map(left) { (function) -> [U] in
return map(right) { return function($0) }
})
}
I'm trying to make it more general by rewriting it to use sequences instead of arrays, but I'm having difficulty with the syntax to require that a sequence be a sequence of functions. This works to generalize the right argument, but not the left:
public func <*> <T, U, Tseq:SequenceType where Tseq.Generator.Element == T>(left:[(T)->U], right:Tseq) -> [U] {
return flatten(map(left) { (function) -> [U] in
return map(right) { return function($0) }
})
}
Now I'm trying to generalize the left part, but running into syntax errors. It seems like it ought to be:
public func <*> <
T,
U,
Tseq:SequenceType where Tseq.Generator.Element == T,
Fseq:SequenceType where Fseq.Generator.Element == (T) -> U
>(left:[(T)->U], right:Tseq) -> [U] {
return flatten(map(left) { (function) -> [U] in
return map(right) { return function($0) }
})
}
But that gives me an error on the Fseq... line:
Expected '>' to complete generic parameter list
What is the proper syntax (or is there no proper syntax) to require that Fseq.Generator.Element be a function taking a T and returning a U?
Couple of problems (one fixable, one more fatal):
You have the syntax for the generic template a bit off. There’s only one where clause for all the placeholders, rather than an optional one per placeholder. So it would be more like:
public func <*> <
T, U, Tseq: SequenceType, Fseq: SequenceType
where Fseq.enerator.Element == T -> U,
Tseq.Generator.Element == T>
(left:[(T)->U], right:Tseq) -> [U] {
return flatten(map(left) { (function) -> [U] in
return map(right) { return function($0) }
})
}
However, that still won’t work because you can’t have expressions more complex than single types on the rhs of a == (not even tuples of two placeholders). So where Fseq.Generator.Element == T->U is not going to fly.
You might want to look at how swiftz does this – looks like it requires an additional struct.

Define function inside \score in LilyPond

I compile a large song book, and for that I would like to have many local definitions of functions, that will, in the end, be in an \include d file, but that makes no difference here. For this, I need to define the functions inside \score{ ... } scope. However, LilyPond keeps throwing errors.
The non-working example:
\version "2.17.26"
\book {
\header {
title = "This is a book"
}
\score {
xyz = { a' b' c'' }
abc = #(define-music-function
( parser location musicnotes )
( ly:music? )
#{
c' $musicnotes e'
#}
)
{ \abc { d' } f' \xyz }
\header {
piece = "First piece"
opus = "op. 1024"
}
}
\score {
xyz = { a' a' a' }
abc = #(define-music-function
( parser location musicnotes )
( ly:music? )
#{
e' $musicnotes c'
#}
)
{ \abc { d' } f' \xyz }
\header {
piece = "Second piece"
opus = "op. 1025"
}
}
}
Throws an error:
test.ly:10:17: error: unrecognized string, not in text script or \lyricmode
xyz = { a' b' c'' }
The following works, however, I have to give the functions unique names, which is frowned upon.
\version "2.17.26"
xyz = { a' b' c'' }
abc = #(define-music-function
( parser location musicnotes )
( ly:music? )
#{
c' $musicnotes e'
#}
)
xxyz = { a' a' a' }
aabc = #(define-music-function
( parser location musicnotes )
( ly:music? )
#{
e' $musicnotes c'
#}
)
\book {
\header {
title = "This is a book"
}
\score {
{ \abc { d' } f' \xyz }
\header {
piece = "First piece"
opus = "op. 1024"
}
}
\score {
{ \aabc { d' } f' \xxyz }
\header {
piece = "Second piece"
opus = "op. 1025"
}
}
}
Unfortunatey, it's not possible to stick assignments in a score. You can only put assignments in the following places:
the top level,
inside \display, \header, and \midi blocks
The LilyPond grammar makes this quite clear, even if the rest of the manual is a bit evasive about it. (Look at http://lilypond.org/doc/v2.17/Documentation/contributor/lilypond-grammar , and look for where the assignment rule gets used).
Assuming your assignments are not appropriate for the blocks listed above (which is definitely the case in this example), and assuming that you don't want to do something exotic like go and define your own Scheme modules and figure out how to use them in your LilyPond file, you have two choices:
Define xyz and abc, then define the music that will go into the first score. Then redefine xyz and abc before defining the music for the next score. This works because assignments overwrite whatever was previously there, and because LilyPond defines are generally processed in order. However, if you want some of your defines to be used in both scores and to be the same, you may get confused.
Settle for your approach, though I would pick a prefix or a suffix that makes it clearer which score the define goes with.
The first option would look something like this:
\version "2.18.0"
xyz = { a' b' c'' }
abc = #(define-music-function (parser location musicnotes)
(ly:music?)
#{ c' $musicnotes e' #})
smus_a = { \abc { d' } f' \xyz }
xyz = { a' a' a' }
abc = #(define-music-function (parser location musicnotes)
(ly:music?)
#{ e' $musicnotes c' #})
smus_b = { \abc { d' } f' \xyz }
\book {
\header {
title = "A Book!"
}
\score {
\smus_a
\header { piece = "First piece" }
}
\score {
\smus_b
\header { piece = "Second piece" }
}
}
This also works if the music-defining parts are refactored out into separate LilyPond source files.
It is possible!
But you have to define a command to define the variable or command:
parserDefine =
#(define-void-function (parser location name val)(symbol? scheme?)
(ly:parser-define! parser name val))
This is a void-function and can be called almost anywhere:
\score {
{
% you have to be in your music-expression
\parserDefine xyz { a' a' a' }
% There must be something between parserDefine and the call!
c'' \xyz
\parserDefine abc #(define-music-function
( parser location musicnotes )
( ly:music? )
#{
c' $musicnotes e'
#}
)
a' \abc d'
}
}
If the command is defined, you can call inside your music expressions. After you have done so, the parser needs a little lookahead, so that the variable really is available - here its the c''. You can optionally wrap the expression in another pair of curly braces.

Resources