haskell中具有多参数函数的惰性过滤器 [英] Lazy filter with multi param function in haskell

查看:90
本文介绍了haskell中具有多参数函数的惰性过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个删除json字符串中的空白的函数。 I
需要知道当前正在处理的字符是否被
所包围,如果它位于转义字符<$ c $之后所以我需要两个参数来完成这个
函数。

I'm writing a function that remove white space in a json string. I need to know if the current char I'm processing is surrounded by ", or if it is after a escape char \. So I need two more param for this function.

这是当前的实现,但我不如果
可以使用json字符串上的filter或map来懒惰?

Here is the current implementation. But I don't think it is lazy. How could I make it lazy with "filter" or "map" on the json string?

compressJson :: String -> String
compressJson json = compress json False False ""
    -- compress params: json, inStr, aferEscape, acc
    where compress []          _     _     acc = acc
          compress ('\"' : xs) inStr False acc = compress xs (not inStr) False (acc ++ "\"")
          compress ('\\' : xs) inStr False acc = compress xs inStr       True  acc
          compress (x    : xs) inStr True  acc = compress xs inStr       False (acc ++ ['\\', x])
          compress (x    : xs) True  False acc = compress xs True        False (acc ++ [x])
          compress (x    : xs) False _     acc = compress xs False       False (acc ++ parse x)

          parse c = if c `elem` " \t\n"
              then []
              else [c]


推荐答案

这实际上很懒惰 - 不要使它成为尾递归。

This is actually trivial to make lazy - don't make it tail-recursive.

或多或少像这样我没有测试它)

More or less like this (I didn't test it)

compressJson :: String -> String
compressJson json = compress json False False
    -- compress params: json, inStr, aferEscape
    where compress []          _     _     = ""
          compress ('\"' : xs) inStr False = '\"' : compress xs (not inStr) False
          compress ('\\' : xs) inStr False = compress xs inStr True
          compress (x    : xs) inStr True  = '\\' : x : compress xs inStr False
          compress (x    : xs) True  False = x : compress xs True False
          compress (x    : xs) False _     = parse x ++ compress xs False False

          parse c = if c `elem` " \t\n"
              then []
              else [c]

尾递归和懒惰是彼此直接对立的。尾递归意味着一个函数是使用修改过的参数调用自己的函数。懒惰意味着它会立即返回一个构造函数(即不会在一些不确定数量的递归调用之后)。所以如果你想要一个函数是懒惰的,写下来立即返回部分结果。

Tail recursion and laziness are at direct odds with each other. Tail recursion implies that a function is a call to itself with modified parameters. Laziness implies that it returns a constructor promptly (ie, not after some indeterminate number of recursive calls). So if you want a function to be lazy, write it to return partial results immediately.

这篇关于haskell中具有多参数函数的惰性过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆