Recent Entries 10
- pattern minor 112d agoConcatenating multiple feedback messagesThe goal is to build a `String` from a given set where `Feedback` is an interface and `DeliveryFeedback`, and `ProductFeedback`are its implementing classes. ``` private void formatOrderFeedbackZendeskBody(final ImmutableSet feedback) { StringBuilder feedbackMessage = new StringBuilder("The feedback: "); feedback.forEach( f -> { if (f instanceof DeliveryFeedback) { feedbackMessage .append("\n\nType: ") .append(FeedbackType.DELIVERY) .append("\nReason(s): ") .append( ((DeliveryFeedback) f) .getReasons() .stream() .map(Reason::name) .collect(joining("\n\t\t\t"))); if (((DeliveryFeedback) f).getComment().isPresent()) { feedbackMessage .append("\nComment: ") .append(((DeliveryFeedback) f).getComment().get()); } } else if (f instanceof ProductFeedback) { feedbackMessage .append("\n\nType: ") .append(FeedbackType.PRODUCT) .append("\nReason(s): ") .append( ((ProductFeedback) f) .getReasons() .stream() .map(
- pattern minor 112d agoAn optional_ref<T>I omitted all free operators but the equality comparisons ones because of verbosity. I am glad about any comments and improvements. Motivation I know that optional references are equivalent to pointers and their implementation is just such a wrapper. But I believe they make sense in some circumstances and please correct me if I am wrong. While implementing and using my interval map I needed to return an optional reference in one of its accessor methods, namely `operator[](Key)`. The idea is to get a reference to a stored value or nothing. Thus I did it there with an `std::optional>`. Following this pattern of optional refs led to complications when I tried accessing an `std::optional>` at some other point of time. I couldn't write something like this ``` int a = 0; std::optional> opt{a}; *opt = 42; assert(a == 42); ``` but instead one has to explicitly unwrap the `reference_wrapper` like this ``` opt.value().get() = 42; assert(a == 42); ``` or ``` opt->get() = 42 assert(a == 42); ``` And my motivation for `optional_ref` was born. Source code Here is the complete source code on wandbox. `optional_ref.hpp` ``` #include #include #include #include "range/v3/utility/concepts.hpp" namespace fub { struct bad_optional_access : std::runtime_error { using runtime_error::runtime_error; }; template class optional_ref { public: using element_type = T; using reference = element_type&; using pointer = element_type*; // CONSTRUCTORS optional_ref() = default; template ())> constexpr optional_ref(const optional_ref& other) noexcept : m_pointer{other.get_pointer()} {} constexpr optional_ref(reference element) noexcept : m_pointer{std::addressof(element)} {} // ASSIGNMENT template ())> constexpr optional_ref& operator=(const optional_ref& other) noexcept { m_pointer = other.get_pointer(); } // DESTRUCTOR ~optional_ref() = default; // SWAP
- debug minor 112d agoUse optional to check Null pointer exceptionI currently have something like this: ``` Price price = new Price(); ActualValue actualValue = new ActualValue(); actualValue.setValue(price.getPreviousPrice().getRegion().getValue()); ``` I want to make sure when calling `getRegion()` and `getValue()`, no NPE is thrown, trying to make it write in one line so I thought about using `Optional` Currently what I have is this: ``` Optional.of(price) .flatMap(d -> Optional.ofNullable(d.getPreviousPrice()) .flatMap(p -> Optional.ofNullable(p.getRegion()) .flatMap(m -> Optional.ofNullable(m.getValue())))) .ifPresent(v -> actualValue.setValue(v)); ``` Looks ugly, how can I improve?
- pattern minor 112d agoMaybe type implementationThis supposed to implement a `Maybe` type that can either hold a value `T` or "nothing". It's designed to work well with vectors (that's why I take extra care to noexcept constructors whenever possible). I'm governing the actual data with `::std::aligned_storage`. Note: The `just` member function is a reference to the Haskell `Maybe` data-constructor `Just`. Did I miss anything? ``` #pragma once #include #include #include namespace ads { template class Maybe { public: typedef typename ::std::aligned_storage::type storage_type; typedef T value_type; private: storage_type data; bool is_valid; inline T* ptr() { return reinterpret_cast(&data); } inline T const* ptr() const { return reinterpret_cast(&data); } public: Maybe() noexcept : data(), is_valid(false) {} template Maybe(U&& v) noexcept(::std::is_nothrow_move_constructible::value) : data(), is_valid(false) { create(::std::forward(v)); } Maybe(Maybe const& from) noexcept(::std::is_nothrow_copy_constructible::value) : data(), is_valid(false) { if (from.is_valid) create(*from.ptr()); } Maybe(Maybe&& from) noexcept(::std::is_nothrow_move_constructible::value) : data(), is_valid(false) { if (from.is_valid) create(::std::move(*from.ptr())); } template Maybe& operator=(U&& v) noexcept(::std::is_nothrow_move_constructible::value && ::std::is_nothrow_copy_constructible::value && ::std::is_nothrow_assignable::value) { create(::std::forward(v)); return *this; } Maybe& operator=(Maybe const& from) noexcept(::std::is_nothrow_copy_constructible::value && ::std::is_nothrow_assignable::value) { if (from.is_valid) { create(*from.ptr()); } else { destroy(); } return *this; } Maybe& operator=(Maybe&& from) noexcept(::std::is_nothrow_move_constructible::
- pattern moderate 112d agoSeamlessly migrating <experimental/optional> to <optional>From this Stack Overflow answer, I learned that C++17 will have `__has_include`, which can [make] migrating from experimental to std almost seamless This still leaves the question of how to do it. Doing something like `namespace std { using namespace std::experimental; }` is undefined behaviour, so I came up with this method: optional.h demonstration on coliru ``` #pragma once #if __has_include() # include # define HAS_STD_OPTIONAL #elif __has_include() # include # define HAS_STD_EXPERIMENTAL_OPTIONAL #else # error Must have an optional type, either from or if not supported from . #endif #if defined HAS_STD_OPTIONAL namespace opt { template using optional = std::optional; using bad_optional_access = std::bad_optional_access; using nullopt_t = std::nullopt_t; using in_place_t = std::in_place_t; constexpr auto nullopt = std::nullopt; constexpr auto in_place = std::in_place; template constexpr auto make_optional(T && value) { return std::make_optional(std::forward(value)); } } #elif defined HAS_STD_EXPERIMENTAL_OPTIONAL namespace opt { template using optional = std::experimental::optional; using bad_optional_access = std::experimental::bad_optional_access; using nullopt_t = std::experimental::nullopt_t; using in_place_t = std::experimental::in_place_t; constexpr auto nullopt = std::experimental::nullopt; constexpr auto in_place = std::experimental::in_place; template constexpr auto make_optional(T && value) { return std::experimental::make_optional(std::forward(value)); } } #endif ```
- pattern major 112d agoFiltering out empty OptionalsI want to convert my list of optional strings to a list of strings by getting rid of the empty `Optional`s. Is there a shorter version for achieving this than the following code (except statically importing the methods of `Collectors`)? ``` List> stringsMaybe = Arrays.asList(Optional.of("Hi"), Optional.empty(), Optional.of(" there!")); List strings = stringsMaybe .stream() .filter(Optional::isPresent) .collect(Collectors.mapping(Optional::get, Collectors.toList())); ```
- pattern minor 112d agoOptional Consumer for ifNotPresentAs Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback: ``` public class OptionalConsumer { private Optional optional; private OptionalConsumer(Optional optional) { this.optional = optional; } public static OptionalConsumer of(Optional optional) { return new OptionalConsumer<>(optional); } public OptionalConsumer ifPresent(Consumer c) { optional.ifPresent(c); return this; } public OptionalConsumer ifNotPresent(Runnable r) { if (!optional.isPresent()) r.run(); return this; } ``` } Then : ``` Optional o = Optional.of(...); OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s)) .ifNotPresent(() -> System.out.println("! isPresent")); ```
- pattern minor 112d agoAn attempt at implementing Maybe in C++11I gave a shot at implementing `Maybe` for C++ and a slight twist in my implementation is that it uses `thread_local static` instance of `Just` and `Nothing` + placement `new` operator to minimize the number of (de)allocations. This is the first time I'm using `thread_local` and placement `new` operator, so I could be doing something really wrong here. I would appreciate if you could take a look at the code and give your feedback. Maybe.hpp: ``` #include #include #include namespace ro { /* * A class that may or may not hold a value in it. */ template class Maybe { public: /* * A deleter that doesn't actually delete the pointer. This is used to make sure that * the thread_local static instance on the stack doesn't get deleted when going out * of scope */ struct NoopDeleter { void operator()(Maybe*) {} }; using pointer_t = std::shared_ptr>; /* * Gets an pointer to a Maybe that's nothing */ static pointer_t nothing(); /* * Gets a pointer to a Maybe that just have a value. */ static pointer_t just(const T& value); public: Maybe() = default; virtual ~Maybe() = default; /* * Returns if this Maybe is nothing */ virtual bool isNothing() const = 0; /* * Gets the value, if this instance has one. Throws a runtimer_error otherwise. */ virtual T get() const = 0; /* * Gets the value held or the passed in value otherwise. */ T getOrElse(const T& defaultValue) const { if (isNothing()) { return defaultValue; } return get(); } /* * Gets the value stored or throws the exception as supplied by the method passed in */ T getOrThrow(const std::function& exceptionSupplier) const { if (isNothing()) { throw exceptionSupplier
- pattern minor 112d agoSimple/Naive Implementation of Identity and Maybe Monad in ElixirThis is my first crack at a identity monad and a maybe monad in Elixir: ``` defmodule Monad do @doc "v is value to be wrapped as monadic value" def return(v), do: fn -> v end @doc "m is monad function, mv is monadic value" def bind(m, mv), do: m.(mv.()) end #Simple identity monad id = fn s -> s end h = Monad.return(:ok) r = Monad.bind(id, h) #Maybe monad maybe = fn s -> if is_nil(s), do: :error, else: s end r = Monad.bind(maybe, h) ``` I'd like to see if there is a way to make the monad into a protocol since the return and bind seem to be common to all monads.
- debug minor 112d agoAdding two values in a map, if they existMy code looks like imperative style code. I want to make my code more functional. How I can rewrite my program so it become functional style code? ``` val _map = getMap(); if(_map.contains(x) && _map.contains(y)) Right(_map(x) + _map(y)) else if(_map.contains(x + y)) Right(_map(x + y)) else if(!_map.contains(x)) Left("%d or %d not found".format(x, x + y)) else if(!_map.contains(y)) Left("%d or %d not found".format(y, x + y)) else Left("What is it?") ```