我具有任何输入返回字符串black
的功能。我想将列表中不等于yellow
的每个元素都更改为黑色,并将其作为新列表返回。
使用过滤器并将其映射会从列表中删除我不想做的元素。
我也想使用函数式编程来保留它,lambdas对于循环来说并不老。我知道我可以在map函数中指定过滤条件,但我想避免这种情况
def change_color(color:String):String = {
return "black"
}
val cats = Seq("pink","blue","yellow")
所以输出应该是
Seq("black","black","yellow")
答案 0 :(得分:0)
这是映射函数在集合上的常见应用。您的情况是一个列表。地图的本质是什么?
def change_color(color: String) : String =
if (color == "yellow") "yellow" else "black"
def map[A, B](list: List[A)(f: A => B): List[B] = {
???
}
它将函数从A到B应用于集合的每个元素,因此,在您的情况下,您的函数为String => String
cats.map(change_color _)
cats.map(el => change_color(el))
这只是使用Scala集合及其功能的开始。从这里您可以尝试折叠,平面图,分组,并行处理等。
答案 1 :(得分:0)
或者,您可以使用protected function _login(
$username,
$password,
$forceLogin = false,
$appRefreshInterval = 1800)
{
if (empty($username) || empty($password)) {
throw new \InvalidArgumentException('You must provide a username and password to _login().');
}
// Switch the currently active user/pass if the details are different.
if ($this->username !== $username || $this->password !== $password) {
$this->_setUser($username, $password);
}
// Perform a full relogin if necessary.
if (!$this->isMaybeLoggedIn || $forceLogin) {
$this->_sendPreLoginFlow();
try {
$response = $this->request('accounts/login/')
->setNeedsAuth(false)
->addPost('phone_id', $this->phone_id)
->addPost('_csrftoken', $this->client->getToken())
->addPost('username', $this->username)
->addPost('adid', $this->advertising_id)
->addPost('guid', $this->uuid)
->addPost('device_id', $this->device_id)
->addPost('password', $this->password)
->addPost('login_attempt_count', 0)
->getResponse(new Response\LoginResponse());
} catch (\InstagramAPI\Exception\InstagramException $e) {
if ($e->hasResponse() && $e->getResponse()->isTwoFactorRequired()) {
// Login failed because two-factor login is required.
// Return server response to tell user they need 2-factor.
return $e->getResponse();
} else {
// Login failed for some other reason... Re-throw error.
throw $e;
}
}
$this->_updateLoginState($response);
$this->_sendLoginFlow(true, $appRefreshInterval);
// Full (re-)login successfully completed. Return server response.
return $response;
}
// Attempt to resume an existing session, or full re-login if necessary.
// NOTE: The "return" here gives a LoginResponse in case of re-login.
return $this->_sendLoginFlow(false, $appRefreshInterval);
}
来转换此序列
Partial Function
这将更加简洁。