在下面的代码片段中:
let b: Vec<usize> = a.iter().filter(|x| **x > 5).map(|x| *x).collect();
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来使b成为值向量而不是引用?(代替.map(|x| *x))
有没有类似的东西:
fn iter_values<T : Copy>(c: &Vec<T>) -> std::iter::Map<std::slice::Iter<T>, fn(&T) -> T> {
c.iter().map(|x| *x)
}
Run Code Online (Sandbox Code Playgroud)
可以像这样使用:
let b: Vec<usize> = iter_values(&a).filter(|x| *x > 5).collect();
Run Code Online (Sandbox Code Playgroud) 我想获得结构中特定成员的大小.
sizeof(((SomeStruct *) 0)->some_member) 适合我,但我觉得可能有更好的方法来做到这一点.
我可以#define SIZEOF_ELEM(STRUCT, ELEM) sizeof(((STRUCT *) 0)->ELEM)然后使用SIZEOF_ELEM(SomeStruct, some_member),但我想知道是否已经有更好的内置功能.
我的具体用例是hsc2hs(Haskell C绑定).
pokeArray (plusPtr context (#offset AVFormatContext, filename)) .
take (#size ((AVFormatContext *) 0)->filename) .
(++ repeat '\NUL') $ filename
Run Code Online (Sandbox Code Playgroud) 在GHC 8.6.2上编译这个简短的片段:
{-# LANGUAGE DeriveGeneric, PolyKinds #-}
import GHC.Generics
data Foo f
= FA
| FB (f (Foo f))
deriving (Generic, Generic1)
Run Code Online (Sandbox Code Playgroud)
结果出现此错误:
Can't make a derived instance of ‘Generic1 Foo’:
Constructor ‘FB’ applies a type to an argument involving the last parameter
but the applied type is not of kind * -> *
Run Code Online (Sandbox Code Playgroud)
是不是可以推导出Generic这样的类型?为什么?
以下片段使GHC(在8.6.2和8.4.4中检查)在编译期间卡住:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
import GHC.Exts (Constraint)
data T = T
type family F t (c :: * -> Constraint) :: Constraint
type instance F T c = c T
class F t C => C t where
t :: C T => t
t = undefined
Run Code Online (Sandbox Code Playgroud)
我认为它会被卡住,因为tGHC试图找到C T,这会导致F T C通过类型族扩展F回来C T,这就是它所寻求的(无限循环).
我认为从理论上说,GHC可以告诉它它自己的追求C T,任何依赖自身的东西都可以递归地工作,或者我误解了什么?
附注:在我偶然发现了这种行为,我能够实现我想要的东西,而不通过更换堵塞在编译器的真实的例子 …
haskell typeclass type-families constraint-kinds undecidable-instances
在诸如
r = open(path, encoding="utf-8").read()
Run Code Online (Sandbox Code Playgroud)
(此处为实际行),
Pylint 2.14.5 提供以下建议:
submodules-dedup.py:71:32: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)
Run Code Online (Sandbox Code Playgroud)
如果我理解正确的话,建议将其更改为
with open(path, encoding="utf-8") as f:
r = f.read()
Run Code Online (Sandbox Code Playgroud)
但这真的更好吗?
就我个人而言,我认为它没有任何可读性,至于其他问题,由于引用计数的工作原理,文件不会同时关闭吗?