为什么使用Nix lambdas和?操作员互动是这样吗?

问题描述

尝试使用nix和nix repl时:

Welcome to Nix version 2.3.6. Type :? for help.

nix-repl> pkgs = import <nixpkgs> {}

nix-repl> builtins.typeOf pkgs
"set"

nix-repl> pkgs ? "firefox"
true

nix-repl> func = (n: pkgs ? "firefox")

nix-repl> func null
true

nix-repl> func = (n: pkgs ? n)

nix-repl> func "firefox"
false

我假设func "firefox"将返回true

在本示例中,什么Nix范式或概念解释了func "firefox"返回false的原因?

解决方法

您在?之后写的东西不是表达式:它是属性路径。这样,您就可以执行诸如pkgs ? hello.src之类的强大功能,该功能可以探查pkgs是否具有名为hello的属性,该属性是否具有名为src的属性。

当Nix评估a ? b时,Nix只看名称“ b”,它不考虑“ b”在本地上下文中是否是变量。因此,pkgs ? n是唯一的pkgs集合,其成员的字面名称为“ n”。

这是一个探讨问题的示例repl会话。最后一行显示了我认为您要尝试的解决方案。

nix-repl> pkgs = import <nixpkgs> {}
nix-repl> pkgs ? "firefox"
true
nix-repl> pkgs ? "name"
false
nix-repl> name = "firefox"
nix-repl> pkgs ? name
false
nix-repl> firefox = "name"
nix-repl> pkgs ? firefox
true
nix-repl> pkgs ? "${name}"
true
nix-repl> builtins.hasAttr name pkgs  
true