我正在观看关于Java的演讲,有一次,讲师说:
"可变性是可以的,分享是好的,共享的可变性是魔鬼的工作."
他所指的是以下一段代码,他认为这是一种"极其糟糕的习惯":
//double the even values and put that into a list.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
List<Integer> doubleOfEven = new ArrayList<>();
numbers.stream()
.filter(e -> e % 2 == 0)
.map(e -> e * 2)
.forEach(e -> doubleOfEven.add(e));
Run Code Online (Sandbox Code Playgroud)
然后他继续编写应该使用的代码,即:
List<Integer> doubleOfEven2 =
numbers.stream()
.filter(e -> e % 2 == 0)
.map(e -> e * 2)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
我不明白为什么第一段代码是"坏习惯".对我而言,他们都达到了同样的目标.
考虑以下代码:
#include <iostream>
using namespace std;
int main()
{
int x = 3;
const int i[] = { 1, 2, 3, 4 };
float f[i[3]];
struct S { int i, j; };
const S s[] = { { 1, 2 }, { 3, 4 } };
double d[s[1].j];
}
Run Code Online (Sandbox Code Playgroud)
它运行没有错误.但是,以下内容:
#include <iostream>
using namespace std;
int x = 3;
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // error: array bound is not an integer constant …Run Code Online (Sandbox Code Playgroud) 问题听起来是这样的:编写一个程序,读取数字 n,然后读取 n 个人,对于每个人,读取他们的姓名和年龄,然后返回最年长的人/人。
输入示例:
3
Ion Ionel Ionescu
70
Gica Petrescu
99
Mustafa ben Muhamad
7
Run Code Online (Sandbox Code Playgroud)
输出示例
Oldest is Gica Petrescu (99 years).
Run Code Online (Sandbox Code Playgroud)
到目前为止我的代码:
readPers :: IO(String, Int)
readPers = do
name <- getLine
age <- readLn :: IO Int
return (name, age)
readPerss :: (Ord t, Num t) => t -> [IO (String, Int)]
readPerss n
| n > 0 = readPers : readPerss(n-1)
| otherwise = []
pFunc = do
print "Numer of persons:"
n <- readLn …Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
#include <iostream>
using namespace std;
class X
{
int i;
public:
X(int ii = 0);
};
X::X(int ii) { i = ii; }
int a;
X f1() { return X(); }
int f2() { return a; }
int main() {
f1() = X(1);
f2() = 3;
}
Run Code Online (Sandbox Code Playgroud)
如果你试图运行它,你会得到
错误:左值作为赋值的左操作数需要左值
因此,在第17行
F1()
被认为是左值,而
F2()
不是.解释将对事情的工作方式有很大的帮助.
我有以下内容:
type Name = String
data Prop
= Var Name
| F
| T
| Not Prop
| Prop :|: Prop
| Prop :&: Prop
deriving (Eq, Read)
infixr 2 :|:
Run Code Online (Sandbox Code Playgroud)
Prop类型代表命题公式.命题变量,例如p和q可以用Var"p"和Var"q"表示.
F和T是False和True的常数布尔值.
不代表否定(〜或¬)
:|:和:&:表示析取(/)和结合(/ \)
我们可以写出逻辑命题:
( Var "p" :|: Var "q") :&: ( Not (Var "p") :&: Var "q")
Run Code Online (Sandbox Code Playgroud)
我要做的是:通过使Prop成为Show类的实例,替换Not,:|:和:&:with~,/和/ \,以便以下内容为真:
test_ShowProp :: Bool
test_ShowProp =
show (Not (Var "P") :&: Var "Q") == "((~P)/\Q)"
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的实现:
instance Show Prop where
show (Var p) = p
show (Not (Var …Run Code Online (Sandbox Code Playgroud) c++ ×2
haskell ×2
class ×1
compilation ×1
constants ×1
forms ×1
function ×1
immutability ×1
io ×1
java ×1
java-8 ×1
java-stream ×1
logic ×1
lvalue ×1