如何编写这个可以更改记录中任何项目的简单Monad?

时间:2018-12-25 08:17:05

标签: haskell

我有这些数据类型,这意味着一盒糖果:

data Candy=Candy {name::String,price::Int}

data Box=Box Candy

let toffee=Candy {name="toffee",price=1}

let box=Box {candy=toffee}

我想将Box做成Monad的实例,可以做到这一点:

box>>=x->return x {name="Toffee",price=2}

box>>=x->return x {name="Toffee"}

box>>=x->return x {price=2}

box>>=x->
  if (name x=="toffee") return x {name="Toffee",price=2}
  else return x {name="other"}

我是Haskell的新手,我尝试写这篇文章但失败了:

instance Monad Box where
 return x=Box x
 Box x>>=f=f x

那怎么写这个单子呢?谢谢!

1 个答案:

答案 0 :(得分:1)

正如其他人所指出的,您的示例都不需要Monad。如果省略private void print( int idNum,String idName,String idSec) { // Define the Job Status Message jobStatus.textProperty().unbind(); jobStatus.setText("Creating a printer job..."); // Create a printer job for the default printer PrinterJob job = PrinterJob.createPrinterJob(); if (job != null) { //Show the printer status jobStatus.textProperty().bind(job.jobStatusProperty().asString()); // Get The Printer Job Settings JobSettings jobSettings = job.getJobSettings(); //Get Printer Printer printer = job.getPrinter(); //Setting Data Node node = printThis; id_Name.setText(idName); id_Num.setText(String.valueOf(idNum)); id_Sec.setText(idSec + " section"); //Setting Page-layout PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER, PageOrientation.PORTRAIT, 0, 0, 0, 0); jobSettings.setPageLayout(pageLayout); //Print node boolean printed = job.printPage(pageLayout, node); if (printed) { // End the printer job job.endJob(); } else { //Write error message jobStatus.textProperty().unbind(); jobStatus.setText("Printing Failed"); } } else { //Write Error message jobStatus.setText("Could not create a printer job"); } } >>=,则所有内容均有效。例如:

return

顺便说一句,由于其中一些实际上并未使用expensiveToffee (Box box) = Box (box {name="Toffee",price=2}) isToffee (Box box) = if (name box=="toffee") then Box (box {name="Toffee",price=2}) else Box (box {name="other"}) 的任何字段,因此您可以直接构造Box而不是使用record-update语法。

Candy

或什至跳过此函数的输入,因为它被忽略了:

expensiveToffee2 (Box _box) = Box (Candy {name="Toffee",price=2})