没有人关注 PureScript 吗?
发布于 9 年前 作者 notcome 5537 次浏览 最后一次编辑是 8 年前 来自 分享

一个强类型、可以编译到 JavaScript 的语言。语法上基本抄袭了 Haskell,但去掉了惰性求值和部分语法糖。可以比较方便的与 JavaScript 交互,生成的代码也有一定的可读性。几大特色有: 一、通过 Continuation Monad + do-notation 解决 callback hell。Monad 手写起来其实也是 callback 满天飞,于是很多年前 Haskell 社区就加入了 do-notation 来简化这个问题。这是 PureScript 官方的示例代码:

import Control.Parallel

data Model = Model [Product] [ProductCategory]

loadModel = do
  model <- runParallel $
    Model <$> inParallel (get "/products/popular/")
          <*> inParallel (get "/categories/all")

view (Model ps cs) = do
  renderProducts ps
  renderCategories cs

main = loadModel `runContT` view

二、通过 Typeclass 支持范型。这个有点类似 Swift 的 Protocol 或者 Java 的接口,但更强大。比如说 Java 的接口只能有一个类型参数——其实 Haskell 原本的 Typeclass 也有这个限制,但编译器扩展早干掉了——但是 PureScript 的就支持多参数 Typeclass:

module Stream where

import Data.Maybe
import Data.Tuple
import Data.String

class Stream list element where
  uncons :: list -> Maybe (Tuple element list)

instance streamArray :: Stream [a] a where
  uncons [] = Nothing
  uncons (x : xs) = Just (Tuple x xs)

instance streamString :: Stream String String where
  uncons "" = Nothing
  uncons s = Just (Tuple (take 1 s) (drop 1 s))

三、方便写 DSL。其实我觉得这个最主要还是归功于 Haskell 系语言可以自定义运算符:

import Data.DOM.Free
 
doc = div [ class := "image" ] $ do
  elem $ img [ src := "logo.jpg"
             , width  := 100
             , height := 200
             ]
  text "Functional programming for the web!"

四、定义高阶函数可以有效简化代码:

import Control.Apply

import Graphics.Canvas (getCanvasElementById, getContext2D)
import Graphics.Canvas.Free

closed path = beginPath *> path <* closePath

filled shape = shape <* fill

withContext shape = save *> shape <* restore

scene = withContext do
  setFillStyle "#FF0000"

  filled $ closed do
    moveTo 0 0
    lineTo 50 0
    lineTo 25 50

main = do
  canvas <- getCanvasElementById "canvas"
  context <- getContext2D canvas

  runGraphics context scene

更多可以点击这里

14 回复

PureScript, 还有elm,最近迷上haskell

@xieren58 哈哈,耍起 React 那是真的爽

@notcome 你耍出心得了没,求分享

@xieren58 我耍出的唯一心得是不要碰 PureScript,习惯了 Haskell——啊呸,GHC 的 Haskell,还好意思叫 Haskell 嘛——的错误提示后,看到 PureScript 要疯啊。(在这里公然黑不太好对不对)

哈哈。。。

看这语法,毛骨悚然

@hezedu 这怎么毛骨悚然了,又不要你写类型标记,还有编译器保证你类型正确,多好

ClojureScript 呢?

@xadillax ClojureScript 没类型吧

而且 到现在还没 出 0.1版本。。。。

*script 太多了

@leapon 正解啊,xxx.js漫天飞,xxscript满地跑

倒是比较关注typescript

@hinson0 嗯,和 angularjs2 绑在一起,得一起看

回到顶部