本文介绍了在 Haskell 中柯里化 3 个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用柯里化函数来删除 Haskell 中的三个参数时遇到问题.

I'm having trouble with currying a function to remove three arguments in Haskell.

免责声明:不是课程作业,今天有人向我提出了这个问题,这一直困扰着我.

Disclaimer: Not Coursework, I was asked this question by someone struggling with this today and it's been bugging me.

我们得到的自定义类型/函数是(只能记住类型)

The custom types/functions we were given were (can only remember types)

type MyThing
  = (Char, String)
type MyThings
  = [MyThing]

funcA :: MyThings -> String -> String
funcB :: MyThings -> String -> Int -> String

我们开始于:

funcB as str n = iterate (funcA as) str !! n

并将其减少如下:

funcB as str n = iterate (funcA as) str !! n
funcB as str = (!!) . (iterate (funcA as)) str
funcB as = (!!) . (iterate (funcA as))
funcB as = (!!) . (iterate . funcA) as

然后,卡住了.我们只是想不出如何避免使用最后一个参数.我知道我以前在某处看到过类似的情况,并且有一个解决方案.

Then, stuck. We just can't figure out how to avoid using the last argument. I know I've seen a similar situation somewhere before and there was a solution.

希望一些 Haskell 天才能指出我为什么是个白痴...

Hoping some Haskell genius can point out why I'm being an idiot...

推荐答案

这里你只需要以下三个操作符部分的定律":

All you need here is the following three "laws" of operator sections:

(a `op` b) = (a `op`) b = (`op` b) a = op a b
          (1)          (2)          (3)

以便操作数进入操作符附近的空闲槽.

so that the operand goes into the free slot near the operator.

对于 (.) 这意味着:(a . b) = (a .) b = (. b) a = (.) a b.所以,

For (.) this means that: (a . b) = (a .) b = (. b) a = (.) a b. So,

f (g x) y !! n
= (!!) (f (g x) y) n              by (3)
= ((!!) . f (g x)) y n
= ((!!) . (f . g) x) y n
= ((!!) .) ((f . g) x) y n        by (1)
= (((!!) .) . (f . g)) x y n
= (((!!) .) . f . g) x y n

你应该只做你喜欢的尽可能多的 pointfree 转换,这样结果表达式对你来说仍然可读 - 事实上,更清晰原来的.pointfree"工具有时会产生不可读的结果.

You should only do as much pointfree transformation as you're comfortable with, so that the resulting expression is still readable for you - and in fact, clearer than the original. The "pointfree" tool can at times produce unreadable results.

停在中间完全没问题.如果你手动完成它太难了,你可能也很难阅读它.

It is perfectly OK to stop in the middle. If it's too hard for you to complete it manually, probably it will be hard for you to read it, too.

((a .) . b) xy = (a .) (bx) y = (a .bx) y = a (bxy) 是一个常见模式 您将很快学会立即识别.所以上面的表达式可以很容易地读回

((a .) . b) x y = (a .) (b x) y = (a . b x) y = a (b x y) is a common pattern that you will quickly learn to recognize immediately. So the above expression can be read back fairly easily as

(!!) ((f . g) x y) n = f (g x) y !! n

考虑到 (.) 是关联的:

(a . b . c) = ((a . b) . c) = (a . (b . c))

这篇关于在 Haskell 中柯里化 3 个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:16