Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java05. ДЗ 04, Кравцун Андрей #66

Open
wants to merge 6 commits into
base: 04-functional-java
Choose a base branch
from

Conversation

kravtsun
Copy link

@kravtsun kravtsun commented Apr 6, 2017

Andrey Kravtsun added 4 commits April 7, 2017 01:49
import java.util.ArrayList;
import java.util.Collection;

public final class Collections {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если у класса только 1 конструктор и тот приватный, то final можно не писать

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checkstyle 6.11.2 жалуется конкретно на это. Исправлять?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не

public final class Collections {
private Collections() {}

public static <T, S> Collection<S> map(Function1<? super T, S> f, Collection<T> c) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

см задание, там указаны другие принимаемые и возвращаемые типы

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил, насколько понял условие.

@@ -0,0 +1,42 @@
package ru.spbau.mit;

// extends Function1<T1, Function1<T2, S>>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не надо)

package ru.spbau.mit;

public abstract class Predicate<T> extends Function1<T, Boolean> {
public static final Predicate ALWAYS_TRUE = new Predicate() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generic-параметры?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generic-параметры к классу? к оператору new (извиняюсь заранее, если дико ошибаюсь по фактике)? Или хорошим тоном считается всегда специфицировать параметр у параметризуемого типа, навроде "public static final Predicate ALWAYS_TRUE = new Predicate()"?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generic параметр к типу константы

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не только хорошим тоном, но и обязательным )

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если компилятор его не вывел, если вывел, то указывать не надо

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тогда странно, что после выставления половина тестов перестала компилироваться.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как теперь эта строка выглядит?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

public static final Predicate ALWAYS_TRUE = new Predicate() {...};
Так нормально? Просто я не могу привыкнуть к мысли, что все бинарные операции несимметричны, поэтому, например, ALWAYS_TRUE нельзя ставить в левую часть бинарного отношения с FAIL_INTEGER.

}
};

public static final Predicate ALWAYS_FALSE = new Predicate() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и здесь

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Прошу пояснения, мы должны давать возможность кастовать Predicate на обобщение T?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не совсем, надо явно указать, что ALWAYS_FALSE готов принимать любые объекты, при этом он должен быть параметризован

private static final Integer MAGIC_2 = -4;
private static final Integer MAGIC_3 = 3;
private static final Integer MAGIC_4 = 10;
private static final Integer MAGIC_5 = -20;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше отключить проверку на константы в тестах

и не использовать обертки без надобности

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

checkstyle.xml находится не в моем репозитории. Был бы рад отключить проверку на константы, если бы знал, что сделаю это всего один раз.

private static final Integer MAGIC_4 = 10;
private static final Integer MAGIC_5 = -20;

private static final ArrayList<Integer> INT_ARR = new ArrayList<Integer>() { {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrays.asList(...)

}
};

private static final List<Object> EMPTY_ARR = new ArrayList<>();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Collections.emptyList()

assertEquals(0, Collections.foldr(FAIL_FUNCTION, EMPTY_ARR, 0));

}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wildcardы надо проверять

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вставил пару тестов. Что конкретно необходимо проверить?

private static final Predicate<Double> EQUAL_TO_ONE = new Predicate<Double>() {
@Override
public Boolean apply(Double arg) {
return ONE_DOUBLE == arg;
Copy link

@sproshev sproshev Apr 10, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нельзя, это объекты, лучше Objects.equals(ONE_DOUBLE, arg). тот сперва проверит на ==, потом вызовет O_D.equals(arg)

-1

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил.

Copy link

@sproshev sproshev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8.5

}

@Override
public abstract Boolean apply(T arg);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это не требуется, мы же его унаследуем от Function1<T, Boolean>


private static final Predicate<Object> NOT_NULL = IS_NULL.not();

private static final List<Object> EMPTY_ARR = (List<Object>) emptyList();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

каст ни к чему

final ArrayList<Integer> positiveOnly = new ArrayList<Integer>() { {
add(-MAGIC_2);
add(-MAGIC_5);
} };
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrays.asList

}
};
final int ten = 10;
assertEquals(Arrays.asList(ten), Collections.filter(isTen, INT_ARR));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если хочется создать список из 1 элемента, лучше использовать Collections.singletonList(...), так не будет создаваться массив, который будет передан в качестве варарга в Arrays.asList

assertEquals(EMPTY_ARR, Collections.takeUnless(IS_POSITIVE_INTEGER.not(), INT_ARR_NEGATED));
assertEquals(Arrays.asList(-1), Collections.takeUnless(IS_POSITIVE_INTEGER, INT_ARR_NEGATED));
assertEquals(INT_ARR, Collections.takeUnless(Predicate.ALWAYS_FALSE, INT_ARR));
ArrayList<Objects> nullArr = new ArrayList<>();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<Integer>

@Test
public void foldl() throws Exception {
final Integer result = 10;
assertEquals(result, Collections.foldl(MINUS, INT_ARR, (Integer) 0));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

каст литерала к обертке не требуется, это выполнится автоматически

import static org.junit.Assert.*;

public class Function1Test {
private static Function1<Integer[], Collection<Integer>> fromArrayToCollection =
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

final, caps

for (Object o : arg) {
c.add((Integer) o);
}
return c;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return Arrays.asList(arg);

}
};

private final Function2<Integer, Integer, Integer> minus = new Function2<Integer, Integer, Integer>() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unused

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants