我能够理解Haskell中无点函数的基础知识:
addOne x = 1 + x
Run Code Online (Sandbox Code Playgroud)
当我们在等式的两边看到x时,我们简化它:
addOne = (+ 1)
Run Code Online (Sandbox Code Playgroud)
令人难以置信的是,在不同的部分中使用相同参数两次的函数可以无点编写!
让我把这个average函数作为一个基本的例子写成:
average xs = realToFrac (sum xs) / genericLength xs
Run Code Online (Sandbox Code Playgroud)
似乎无法简化xs,但http://pointfree.io/提出:
average = ap ((/) . realToFrac . sum) genericLength
Run Code Online (Sandbox Code Playgroud)
这样可行.
据我所知,这说明average与调用ap两个函数相同,即(/) . realToFrac . sum和的组合genericLength
不幸的是,这个ap函数对我没有任何意义,文档http://hackage.haskell.org/package/base-4.8.1.0/docs/Control-Monad.html#v:ap状态:
ap :: Monad m => m (a -> b) -> m a -> m b
In many situations, the liftM operations can be …Run Code Online (Sandbox Code Playgroud) 一个纯粹的 功能类似于一个数学函数,在那里与"现实世界",也不副作用没有交互的功能.从更实际的角度来看,这意味着纯函数不能:
所有这些限制使得更容易推理纯函数而不是非纯函数.然后,大多数函数应该是纯函数,以便程序可以减少错误.
在像Haskell这样的庞大类型系统的语言中,如果函数是纯粹的或者不是纯粹的,读者可以从一开始就知道,使得连续阅读更容易.
在Python中,这些信息可以由@pure放在函数顶部的装饰器模拟.我也希望那个装饰器实际上做一些验证工作.我的问题在于这种装饰器的实现.
现在我只是看一下流行语的功能的源代码,如globalor random或print抱怨,如果找到其中一个.
import inspect
def pure(function):
source = inspect.getsource(function)
for non_pure_indicator in ('random', 'time', 'input', 'print', 'global'):
if non_pure_indicator in source:
raise ValueError("The function {} is not pure as it uses `{}`".format(
function.__name__, non_pure_indicator))
return function
Run Code Online (Sandbox Code Playgroud)
然而,感觉就像一个奇怪的黑客,根据你的运气可能会或可能不会工作,你能帮我写一个更好的装饰?
python formal-verification metaprogramming decorator purely-functional
二维列表如下:
1 | 2 | 3
- - - - -
4 | 5 | 6
- - - - -
7 | 8 | 9
Run Code Online (Sandbox Code Playgroud)
或者在纯粹的哈克尔
[ [1,2,3], [4,5,6], [7,8,9] ]
Run Code Online (Sandbox Code Playgroud)
预期的输出diagonals [ [1,2,3], [4,5,6], [7,8,9] ]是
[ [1], [4, 2], [7, 5, 3], [8, 6], [9] ]
Run Code Online (Sandbox Code Playgroud)
写作allDiagonals(包括反对角线)是微不足道的:
allDiagonals :: [[a]] -> [[a]]
allDiagonals xss = (diagonals xss) ++ (diagonals (rotate90 xss))
Run Code Online (Sandbox Code Playgroud)
类似的问题在StackOverflow
Hoogle
搜索给[[a]] -> …
我正在阅读Haskell Prelude并发现它非常容易理解,然后我偶然发现了exponention的定义:
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
Run Code Online (Sandbox Code Playgroud)
我不明白需要两个嵌套where的.
到目前为止我所理解的:
(^) :: …Run Code Online (Sandbox Code Playgroud) 我是 PyTorch、GAN 的新手,并且我在 Python 方面没有太多经验(尽管我是 C/C++ 程序员)。
\n我有一个简单的 DCGAN 教程代码,用于生成假图像,当我使用 \xe2\x80\x9cDATASETNAME = \xe2\x80\x98MNIST\xe2\x80\x99\xe2\x80\x9d 运行代码时,一切正常。但是,当我将数据集更改为 \xe2\x80\x98CIFAR10\xe2\x80\x99 时,程序会产生与 \xe2\x80\x9crunning_mean\xe2\x80\x9d 相关的错误。
\n代码如下
\nimport torch.nn as nn\n\ndef weights_init(module):\n\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d):\n module.weight.detach().normal_(mean=0., std=0.02)\n elif isinstance(module, nn.BatchNorm2d):\n module.weight.detach().normal_(1., 0.02)\n module.bias.detach().zero_()\n else:\n pass\n\nclass View(nn.Module):\n\n def __init__(self, output_shape):\n super(View, self).__init__()\n self.output_shape = output_shape\n\n def forward(self, x):\n return x.view(x.shape[0], *self.output_shape)\n\n\nclass Generator(nn.Module):\n\n def __init__(self, dataset_name):\n super(Generator, self).__init__()\n act = nn.ReLU(inplace=True)\n norm = nn.BatchNorm2d\n\n if dataset_name == 'CIFAR10': # Output shape 3x32x32\n model …Run Code Online (Sandbox Code Playgroud) 在rebol中我写了这个非常简单的函数:
make-password: func[Length] [
chars: "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"
password: ""
loop Length [append password (pick chars random Length)]
password
]
Run Code Online (Sandbox Code Playgroud)
当我连续多次运行时,事情变得非常混乱:
loop 5 [print make-password 5]
Run Code Online (Sandbox Code Playgroud)
给(例如)此输出:
看起来这个函数记住了过去的执行并存储了结果而不是再次使用它!
我没问过这个!
我希望输出类似于以下内容:
我怎样才能达到这个效果?
这个非常简单的脚本:
REBOL []
view layout [
button "Rand" [alert to-string random 100]
]
Run Code Online (Sandbox Code Playgroud)
给出以下结果:
这显然不是随机的,因为相同的数字一遍又一遍地重复.
我编写了两个函数来检查Haskell中的数字是否为素数:
prime :: Int -> Bool
prime 0 = False
prime 1 = False
prime 2 = True
prime n | even n = False
prime n = all (\x -> n `rem` x /= 0) [3,5..intSqrt]
where intSqrt = (floor . sqrt . fromIntegral) n
prime2 :: Int -> Bool
prime2 0 = False
prime2 1 = False
prime2 n = all (\x -> n `rem` x /= 0) [2..intSqrt]
where intSqrt = (floor . sqrt . fromIntegral) n …Run Code Online (Sandbox Code Playgroud) 我有这个非常简单的代码:
from typing import List, Iterable
Position = (int, int)
IntegerMatrix = List[List[int]]
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
"""Given an NxM matrix find the positions that contain a zero."""
for row_num, row in enumerate(matrix):
for col_num, element in enumerate(row):
if element == 0:
yield (col_num, row_num)
Run Code Online (Sandbox Code Playgroud)
这是错误:
Traceback (most recent call last):
File "type_m.py", line 6, in <module>
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
File "/usr/lib/python3.5/typing.py", line 970, in __getitem__
(len(self.__parameters__), len(params)))
TypeError: Cannot change parameter count from 1 to 2 …Run Code Online (Sandbox Code Playgroud)