Sau*_*ade 54 python haskell functional-programming partial-application partial-functions
According to my understanding, partial functions are functions that we get by passing fewer parameters to a function than expected. For example, if this were directly valid in Python:
>>> def add(x,y):
... return x+y
...
>>> new_function = add(1)
>>> new_function(2)
3
Run Code Online (Sandbox Code Playgroud)
In the snippet above, new_function
is a partial function. However, according to the Haskell Wiki, the definition of partial function is
A partial function is a function that is not defined for all possible arguments of the specified type.
so, my question is: what exactly is meant by "partial function"?
Wil*_*sem 74
您在这里混淆了两个概念。甲部分施加函数 [Haskell的维基]具有部分功能 [Haskell的维基]。
部分应用的功能是:
Haskell中的部分应用程序涉及将少于完整数量的参数传递给带有多个参数的函数。
而部分函数确实是一个非全部函数:
局部函数是未针对指定类型的所有可能参数定义的函数。
sep*_*p2k 20
维基说的就是部分函数(在函数编程和数学上下文中):函数未针对其所有可能的参数进行定义。在编程的上下文中,我们通常将“未定义”解释为以下几种情况之一,包括未定义的行为,异常或不终止。
偏函数的一个示例是整数除法,如果除数为0(在Haskell中它将抛出错误),则该整数函数未定义。
在上面的代码段中,new_function是局部函数。
该代码只会在Python中引起错误,但如果按您的预期工作,它将是一个完整的功能(不是部分功能)。
正如评论员已经指出的那样,您很可能会想到它是部分应用功能的事实。
Dam*_*ero 16
答案说明全部,我将只用每种语言添加一个示例:
def add(x,y):
return x+y
f = add(1)
print(f(3))
f = add(1)
TypeError: add() missing 1 required positional argument: 'y'
Run Code Online (Sandbox Code Playgroud)
这既不是部分函数也不是咖喱函数,这只是一个您没有给出所有参数的函数。
python中的咖喱函数应该是这样的:
partialAdd= lambda x: lambda y: x + y
plusOne = partialAdd(1)
print(plusOne(3))
4
Run Code Online (Sandbox Code Playgroud)
在haskell中:
plus :: Int -> Int -> Int
plus x y = x + y
plusOne = plus 1
plusOne 4
5
Run Code Online (Sandbox Code Playgroud)
python中的部分函数:
def first(ls):
return ls[0]
print(first([2,4,5]))
print(first([]))
Run Code Online (Sandbox Code Playgroud)
输出
2
print(first([]))
File "main.py", line 2, in first
return ls[0]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
在Haskell中,如您的链接所示:
head [1,2,3]
3
head []
*** Exception: Prelude.head: empty list
Run Code Online (Sandbox Code Playgroud)
那么什么是总功能?
好吧,基本上相反:这是一个适用于该类型任何输入的函数。这是python中的示例:
def addElem(xs, x):
xs.append(x)
return xs
Run Code Online (Sandbox Code Playgroud)
如果您使用一些技巧,这甚至适用于无限列表:
def infiniList():
count = 0
ls = []
while True:
yield ls
count += 1
ls.append(count)
ls = infiniList()
for i in range(5):
rs = next(ls)
print(rs, addElem(rs,6))
[1, 2, 3, 4]
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
相当于Haskell:
addElem :: a -> [a] -> [a]
addElem x xs = x : xs
addElem 3 (take 10 [1..])
=> [3,1,2,3,4,5,6,7,8,9,10]
Run Code Online (Sandbox Code Playgroud)
在这里,这些功能不会永远挂起。概念是相同的:对于每个列表,功能都会起作用。
归档时间: |
|
查看次数: |
4129 次 |
最近记录: |