https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
arrow
  • p

    Philipp Mayer

    10/19/2021, 2:25 PM
    Hello everyone, I’m trying to get my hands dirty with arrow + project reactor. I have the following code snippet which does not work:
    import arrow.core.Either
    import arrow.core.left
    import arrow.core.right
    import reactor.core.publisher.Mono
    
    fun doSomething(): Mono<Either<String, Boolean>> = Mono.just(1).flatMap { listingId ->
        handle(listingId)
    }
    
    fun handle(x: Int): Either<String, Mono<Boolean>> =
        if (x == 1) Mono.just(true).right()
        else "something else".left()
    Basically I return either a mono of some value or a default value which is not a mono (but could be if it makes things easier). In
    applyforFinancing
    I want to return the result of
    ::handle
    , but that gives me:
    Type mismatch.
    Required:
    Either<String, Mono<Boolean>>
    Found:
    Mono<(???..???)>
    How could one achieve that? Basically I somehow have to transform an
    Either<Mono<…>, Mono<…>
    to
    Mono<Either<…,…>
    Thanks in advance!
    c
    s
    • 3
    • 14
  • m

    Marius Kotsbak

    10/20/2021, 3:19 PM
    @simon.vergauwen https://github.com/arrow-kt/Arrow-JS-Template looks like not working now. Except that it refer to SNAPSHOT-versions it could not find, I get this kind of errors:
    * What went wrong:
    Could not determine the dependencies of task ':packageJson'.
    > Could not resolve all dependencies for configuration ':npm'.
       > Could not resolve io.arrow-kt:arrow-core:1.0.0.
         Required by:
             project :
          > No matching variant of io.arrow-kt:arrow-core:1.0.0 was found. The consumer was configured to find a usage of 'kotlin-runtime' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js', attribute 'org.jetbrains.kotlin.js.compiler' with value 'legacy' but:
              - Variant 'commonMainMetadataElements' capability io.arrow-kt:arrow-core:1.0.0:
                  - Incompatible because this component declares a usage of 'kotlin-api' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'common' and the consumer needed a usage of 'kotlin-runtime' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js'
                  - Other compatible attribute:
                      - Doesn't say anything about org.jetbrains.kotlin.js.compiler (required 'legacy')
    r
    s
    • 3
    • 9
  • p

    Peter

    10/22/2021, 4:38 PM
    i’m curious what people’s opinions are about the kotlin builder pattern DSL, eg: https://github.com/ktorio/ktor/blob/main/ktor-server/ktor-server-core/jvm/src/io/ktor/server/util/URLBuilder.kt#L31 using: https://github.com/ktorio/ktor/blob/main/ktor-http/common/src/io/ktor/http/URLBuilder.kt mutable state as far as the eye can see 🙂 but the actual DSL function
    url
    has mutable state constrained locally and should still be referentially transparent i believe, does this pattern have a place in functional kotlin?
    e
    r
    • 3
    • 3
  • i

    ibcoleman

    10/23/2021, 10:49 PM
    Hi all! I’m coming back to kotlin and arrow after a bit of time away, and I’m having a little difficulty putting the pieces together--especially given the huge changes from 0.11 -> 1.0.0. I’m trying to compose functions that return
    Observable<Either<T, U>>
    and though the
    either {}
    stuff is pretty straightforward, the only documentation I can find on nested monads is the old EitherT, OptionT documentation. Here
    Observable
    is from rxjava2. What if I wanted to use a Reader and had to deal with
    Reader<Observable<Either<MyError, Aggregate
    ? Just very confused…
    @Test
        fun checkCallsWithEitherComprehensionTest() = runBlocking {
    
            fun together(asset: Asset, agg: Aggregate): Either<MyError, AssetWithAggregate> =
                Right(AssetWithAggregate(assetName = asset.name, aggName = agg.name, id = asset.id))
    
            fun getAggregate(): Observable<Either<MyError, Aggregate>> =
                Observable.just(Right(Aggregate(id="000", name="An Aggregate")))
    
            fun getAsset(id: String): Observable<Either<MyError, Asset>> =
                Observable.just(Right(Asset(id=id, name="An Asset")))
    
            // How do I get rid of blockingSingle() to defer this stuff?
            val togetherE: Either<MyError, AssetWithAggregate> = either {
                val theAgg = getAggregate().blockingSingle().bind()
                val theAsset = getAsset(theAgg.id).blockingSingle().bind()
                together(theAsset, theAgg).bind()
            }
    
            // Check the values of the returned Either
            togetherE.fold(
                {_ -> assertTrue(false, "Error: Should be right!")},
                {
                    assertEquals("An Asset", it.assetName)
                    assertEquals("An Aggregate" , it.aggName)
                    assertEquals("000", it.id)
                }
            )
        }
    r
    s
    • 3
    • 7
  • m

    Michael Friend

    10/25/2021, 3:08 PM
    Whats the timeline on a 1.0.1 release with the fixed kmp metadata file? As far as i can tell its a hard blocker for using arrow-core in common code, is there currently a workaround in the meantime?
    s
    • 2
    • 6
  • b

    Benoît

    10/26/2021, 9:59 AM
    Hi everyone, Is there a NonEmptySet in arrow? I can't find it
    s
    r
    • 3
    • 11
  • m

    Marius Kotsbak

    10/28/2021, 11:26 AM
    Hmm, this deprecation message is wrong?:
    @Suppress("ClassName")
    @Deprecated(
      "The `either` computation block supports validated with the right short-circuiting semantics",
      ReplaceWith("either", "arrow.core.computations.either")
    )
    object validated {
      inline fun <E, A> eager(crossinline c: suspend RestrictedValidatedEffect<E, *>.() -> A): Validated<E, A> =
        Effect.restricted(eff = { RestrictedValidatedEffect { it } }, f = c, just = { it.valid() })
    
      suspend inline operator fun <E, A> invoke(crossinline c: suspend ValidatedEffect<E, *>.() -> A): Validated<E, A> =
        Effect.suspended(eff = { ValidatedEffect { it } }, f = c, just = { it.valid() })
    }
    As far as I can see .bind() short circuit on first validation error instead of accumulating?:
    suspend fun <B> Validated<E, B>.bind(): B =
        when (this) {
          is Validated.Valid -> a
          is Validated.Invalid -> control().shift(this@bind)
        }
    s
    m
    • 3
    • 28
  • j

    jean

    10/29/2021, 7:16 AM
    I’ve been playing around with arrow to compose functions with a simple use case where I want to fetch different values in order to build a final object. Something like this :
    data class GetUserImageContext(val apiClient: ApiClient)
    
    typealias GetUserImage = suspend GetUserImageContext.(path: String) -> Either<ApiError, UserImage>
    
    fun getUserImage(): GetUserImage = { path -> 
        try {
            // some executiuon
            Either.Right(image)
        } catch(e: Exception) {
            Either.Left(ApiError.SomethingWentWrong)
        }
    }
    This suits me well for unit testing but the problem comes where a function is composed of several like that one. The context object ends up containing too many things :
    data class GetUserContext(
        val getUserImageContext: GetUserImageContext,
        val getUserImage: GetUserImage,
       // keeps on going based on the functions needed for building the final object
    )
    ...
    // I need both the context object and the alias object to be able to get the final value I want
    val image = getUserImage(getUserImageContext, "/some/path")
    I did watch some of the video on youtube talking about this recommended the “Context” approach but they are ~3 years old. Is there a better way to approach this now?
    p
    s
    • 3
    • 6
  • a

    Alvaro Blazquez checa

    11/02/2021, 9:50 AM
    Hi there!. Is there something similar to tap function in Arrow? that is execute a side effect action with the value of a container and return the input of the original container. Example:
    getResultFromDatabase().tap { result ->
      log(result)
    }.map { result ->
      transformDatabaseResult()
    }
    s
    c
    • 3
    • 6
  • c

    colintheshots

    11/02/2021, 9:46 PM
    I'm just getting started with Optics. I know about modify. Is there a method to return a value if it exists in the current sealed class structure or null? EDIT: Nevermind, answered my own question. I just found
    getOrNull()
    ... are there docs of all the functions available somewhere?
    s
    • 2
    • 2
  • c

    conner

    11/03/2021, 11:35 AM
    is there an (idiomatic) way to do
    if let Left(err) = myEitherValue { /* do something with err */ }
    ? basically i want to run a block if
    myEitherValue
    is
    Left
    , and i would like to avoid casting it
    p
    • 2
    • 4
  • t

    than_

    11/03/2021, 3:52 PM
    Hi, just curious. Is there a reason why
    Semigroup
    is not a
    fun interface
    ?
    r
    • 2
    • 2
  • c

    CLOVIS

    11/04/2021, 10:36 AM
    I'm currently learning Rust and especially traits. I've read KEEP-87 as well as the contextual receivers one previously, and I've seen mentioned multiple times that they will allow to implement an interface for a class we don't control. I understand how KEEP-87 and Rust's traits manage this, but how do context receivers enable this?
    r
    • 2
    • 2
  • a

    Alvaro Blazquez checa

    11/04/2021, 12:31 PM
    What is the minimal kotlin version I should be running to use Arrow 1.0.? It seems it is compiled with 1.5.1. Am I correct? Do I have to also update kotlin to 1.5.1?
    s
    • 2
    • 9
  • o

    Ovidiu Ionescu

    11/04/2021, 8:42 PM
    Tried using arrow-kt 1.0.1 and I can not import arrow.core Version 1.0.0 seems to work. Any idea why arrow.core is unavailable in 1.0.1? (project uses maven)
    s
    d
    +3
    • 6
    • 22
  • m

    Marko Novakovic

    11/05/2021, 11:47 AM
    when can we expect updated/new samples?
    s
    • 2
    • 2
  • n

    Nathan Bedell

    11/06/2021, 2:26 PM
    Hey all, I'm not sure if this is the right place for this, as it's kind of a design/ecosystem question -- but I'm looking for the perspective of the FP community programming in Kotlin. I've started experimenting with kotlinx.serialixation recently -- and at first it seemed really promising -- kind of like an ad hoc implementation of a type-class approach to serializers/deserializers, implemented as a compiler plugin. It kind of reminds me a lot of Rust's serde in that sense as well, as it supports a number of different output formats from a single "type-class". This seems to work well, and how I would expect for sealed classes/data classes, but I am confused by the kotlinx.serialization team's decisions regarding the behavior of serializing interfaces. Apparently, interfaces are automatically serializable via "polymorphic serializers" that are registered at run-time. In other words, if I have a data class with a member that is an interface, unless I register a polymorphic serializer (or otherwise manually specify a serializer with
    @Serializable(with=...)
    ), serialization of my data class will fail at run-time, instead of warning me at compile-time that my data class is not serializable. Coming from experience with type-class/trait based approaches to serialization, this is really jarring to me in practice. One of the nice things to me about automatically deriving serializer/deserializers pairs is that it eliminates a whole class of unit/property-based tests I would otherwise have to write to ensure correctness of my program. If there's a possibility my program could crash at run-time because I tried to serialize something that isn't serializable, I still need to write those tests, which can be very tedious/time consuming. However, when I asked a question and suggested at least allowing for users to "opt-out" of the "interfaces are automatically serializable" approach", I got the response: "Open polymorphism is a powerful mechanism that is tied to the runtime by its nature, so giving up on compile-time errors is a tradeoff for convenience." So, I have a couple of questions for the community here: 1. Does anyone understand this design decision, and exactly why this decision from the kotlinx.serialization team is convenient? 2. Is anyone else equally bothered as me from the lack of compile-time type safety in the current implementation of kotlinx.serialization? For 2, perhaps if there is enough support we could open a new feature request specifically asking to be able to opt out of automatic interface serialization at run-time. If the Kotlin team holds to their grounds, there's always the possibility that someone could make a fork, or a more properly type-class based approach, but I'd like to avoid that if possible. Less fragmentation is good!
    s
    • 2
    • 1
  • n

    niltsiar

    11/11/2021, 8:19 AM
    Hi, I was looking at the
    Either
    source code and out of curiosity I was wondering why functions like
    map
    ,
    fold
    ,
    tap
    ... are member functions while
    flatMap
    ,
    getOrElse
    and some other are extension functions.
    s
    r
    • 3
    • 3
  • t

    thanh

    11/11/2021, 4:13 PM
    👋 do we have anything similar to this in optics?
    public fun <A> listPredicate(p: (A) -> Boolean): Optional<List<A>, A> = Optional(
          getOption = { it.firstOrNull(p).toOption() },
          set = { list, newHead ->
            val index = list.indexOfFirst(p)
    
            if (index != -1) list.take(index) + newHead + list.drop(index + 1) else list
          }
        )
    s
    • 2
    • 20
  • j

    jean

    11/11/2021, 7:45 PM
    How would you people improve this code?
    suspend fun <T> getListWrapperFromDbAnApi(
        getFromDb: suspend () -> Either<InOrderError, ListWrapper<T>>,
        shouldUpdate: (List<T>) -> Boolean,
        getFromApi: suspend () -> Either<InOrderError, ListWrapper<T>>,
        saveDataFromApi: suspend (List<T>) -> Either<InOrderError, Unit>
    ) = flow {
            getFromDb().fold(
                { emit(Either.Left(it)) },
                { dbData ->
                    emit(Either.Right(dbData))
                    if (shouldUpdate(dbData.items)) {
                        getFromApi().fold(
                            { emit(Either.Left(it)) },
                            { apiData ->
                                if (dbData != apiData) {
                                    emit(Either.Right(apiData))
                                    saveDataFromApi(apiData.items)
                                }
                            }
                        )
                    }
                }
            )
        }
    I don’t think I can use
    either.eager
    due to the nested suspend function error
    Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope
    s
    p
    • 3
    • 9
  • s

    SecretX

    11/14/2021, 7:30 PM
    Where did
    Option.applicative()
    went with release 1.0? What should I use instead? I'm looking for a way to compose these three
    Option
    into an object, or
    null
    otherwise:
    // example of expected input for string: "10 -55 99"
    private fun parseLocation(string: String, dungeonName: String): Location? {
        val args = string.split(' ', limit = 3)
        if (args.size != 3) {
            logger.warning("Invalid location '$string' for dungeon '$dungeonName', skipping this location for now")
            return null
        }
        val x = args[0].toIntOrNull().toOption()
        val y = args[1].toIntOrNull().toOption()
        val z = args[2].toIntOrNull().toOption()
        // use x y and z to create a location
    }
    s
    • 2
    • 3
  • h

    HieiJ

    11/15/2021, 9:01 PM
    Hi, I'm playing a bit with the computation blocks; I'm trying to understand what is the best way to compose blocks for nested monads. As an example:
    val str1 = "hello".toOption().right()
        val str2 = "world".toOption().right()
    
        val output: Either<Any, Option<String>> = either {
            option {
                val value1 = str1.bind().bind()
                val value2 = str2.bind().bind()
                value1 + value2
            }
        }
    I'm wondering if there is any "generic" way compose in order to obtain (for this example) an
    eitherOption { }
    block where I can call
    .bind()
    just one time. I know that Option and Either nested like this are not so useful, this is just for having a simple example 😃
    s
    • 2
    • 6
  • m

    Milse113

    11/16/2021, 1:28 AM
    I’m having some trouble importing Arrow’s refinement types plugin, can anyone help? Here’s the relevant parts of the gradle file :) :
    plugins {
        kotlin("jvm") version "1.5.0"
        java
        id("io.arrow-kt.refined-types") version "1.0.1"
    }
    
    buildscript {
        repositories {
            mavenCentral()
            maven(url = "<https://oss.sonatype.org/content/repositories/snapshots/>")
        }
    }
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation(kotlin("stdlib"))
        implementation("io.arrow-kt:arrow-meta:1.0.1")
        implementation("io.arrow-kt:arrow-refined-types:1.0.1")
        implementation("io.arrow-kt:arrow-core:1.0.1")
        ...
    }
    r
    j
    a
    • 4
    • 88
  • p

    Peter

    11/17/2021, 3:33 AM
    hi all - noticed there doesn’t appear to be many great kotlin JWT libraries, took a stab at one over the weekend, making heavy use of Arrow: https://github.com/nefilim/kjwt the kotlin type system remains a bit challenging/limiting, need to take another pass now that 1.6 is out with apparently improved type inference. any feedback/suggestions welcome!
    ❤️ 5
    s
    • 2
    • 2
  • n

    Norbi

    11/17/2021, 10:35 AM
    Hello, is there a plan for creating an Arrow/Optics version supporting Kotlin/JS/IR as well? Thanks. https://kotlinlang.slack.com/archives/C013BA8EQSE/p1637103637144600
    s
    • 2
    • 5
  • i

    Ivan Lorenz

    11/18/2021, 1:52 PM
    Hi all, FP newbie here trying to do a deep dive into
    Arrow
    and playing today with
    Validated
    . As a learning exercise to explain myself and others if Validated is an
    Applicative
    I am checking wether it satisfies Functor and Applicative laws. I am doing that verification using
    Kotest
    using a specific instance of
    Validated<Nothing, String?>
    - so really only formally checking those laws against that specific Type. I got stuck at verifying
    Interchange
    and
    Composition
    law for
    Applicative
    and finally came up with this try for both:
    "Validated applicative must satisfy interchange law" {
            checkAll(genNullableString) { a ->
                val f = { b: String? -> "PRE-APPENDED${b}" }
                val validatedF1 = Validated.lift<Nothing, String?, String?>(f)
                val validatedF2 = Validated.lift<Nothing, (String?) -> String?, String?> { f -> f(a) }
                validatedF1(a.valid()) shouldBe validatedF2(f.valid())
            }
        }
    "Validated applicative must satisfy composition law" {
            checkAll(genNullableString) { a ->
                val f = { b: String? -> "PRE-APPENDED${b}" }
                val g = { b: String? -> "${b}POST-APPENDED" }
                val validatedF1 = Validated.lift<Nothing, String?, String?>(f)
                val validatedF2 = Validated.lift<Nothing, String?, String?>(g)
                (validatedF2.compose(validatedF1))(a.valid()) shouldBe validatedF1(validatedF2(a.valid()))
            }
        }
    I am not sure if I have been able to replicated in
    Kotlin
    and
    Kotest
    what in Haskell would have been: •
    u <*> pure y *=* pure ($ y) <*> u
    for Interchange law and, •
    pure (.) <*> u <*> v <*> w *=* u <*> (v <*> w)
    for Composition law Are the above Kotest tests really checking what Interchange and Composition laws are for Applicatives? Or I am completely lost? Thank you very much for bringing
    Arrow
    to us.
    r
    • 2
    • 5
  • m

    mbonnin

    11/18/2021, 3:17 PM
    Hi 👋 Arrow newbie here. I'm trying to modify deeply nested immutable data classes which sounds exactly like what Optics are for but I'm having a hard time wrapping my head around it. Is there a sample of how to do this somewhere? Ideally something that does the equivalent of the (simple) example below?
    // How do I do this with Optics?
    val user = user.copy(
      address = user.address.copy(
        city = newCity
      )
    )
    👀 1
    t
    • 2
    • 7
  • t

    Ties

    11/18/2021, 4:01 PM
    Arrow question 🙂 Im busy developing a talk about the arrow framework for a conference, Its going quite well (although finding good examples in researching arrow was kinda hard). And in my research I managed to get refined types working (although I have not been able to get the compile errors to show in intellij? (can anyone help with that?)) but I think I read somewhere that this will be rebuild in december? (in that case I do not want to put it in the talk yet and rather wait for a more stable version)
    r
    a
    • 3
    • 6
  • a

    Alvaro Blazquez checa

    11/19/2021, 7:31 AM
    Hi guys. I need an equivalent for:
    val result:Try<T> = Try.applicative().tupled()
    s
    • 2
    • 10
  • a

    Alvaro Blazquez checa

    11/19/2021, 1:40 PM
    Hi again!. Does anyone know equivalent to:
    arrow.core.andThen
    in 1.0??
    s
    • 2
    • 27
Powered by Linen
Title
a

Alvaro Blazquez checa

11/19/2021, 1:40 PM
Hi again!. Does anyone know equivalent to:
arrow.core.andThen
in 1.0??
s

simon.vergauwen

11/19/2021, 1:41 PM
https://arrow-kt.io/docs/apidocs/arrow-core/arrow.core/index.html#functions
a

Alvaro Blazquez checa

11/19/2021, 1:42 PM
I did use andThen to add another step to a function type
I think it is not the same
s

simon.vergauwen

11/19/2021, 1:42 PM
The signature hasn’t changed, it moved to a different package
can you share a snippet?
a

Alvaro Blazquez checa

11/19/2021, 1:42 PM
sure
https://arrow-kt.io/docs/0.11/apidocs/arrow-core-data/arrow.core/-and-then/
I was looking for that andThen @simon.vergauwen. to do function composition
Since higherkinds are deprecated in 1.0 i dont know if that is still available
s

simon.vergauwen

11/19/2021, 8:45 PM
It’s still available here. https://github.com/arrow-kt/arrow/blob/main/arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/composition.kt#L8
Oh, you’re looking for the higher kind?
This is now being used underneath
andThen
and you no longer need to keep
AndThen
around
You can safely use
typealias AndThen<A> = () -> A
to replace it
a

Alvaro Blazquez checa

11/19/2021, 8:52 PM
i need to check that out. I dont get it right now. Thx
migrating to 1.0 old andThen use gives me an error. It was used over an exetenssion function so: MyClass.() -> Try<T> was the signature of the function I was using andThen over, like:
val a: MyClass.() -> Try<T> = createFunction().andThen()
now migrating to 1.0 it does not compile
i have checked old signature of andThen ans was:
infix fun <A, B, C> ((A) -> B).andThen(g: (B) -> C): (A) -> C
now it is:
public expect infix fun <P1, IP, R> ((P1) -> IP).andThen(f: (IP) -> R): (P1) -> R
So for example:
val a: () -> String = { " 2323" }.andThen { s -> s }
val b: Myclass.() -> String = { " 2323" }.andThen { s -> s }
b does not comiple now in 1.0
cant figure out why
Ok. my fault. Extension function I was applying and Then to was refactored to suspend. That is why compiler was complaining because receiver of andThen was different. 😑.
😅 1
s

simon.vergauwen

11/21/2021, 11:39 AM
I think it’d be interesting to add
suspend
variants of those functions maybe? If you’re interested feel free to create a issue/PR 😉
a

Alvaro Blazquez checa

11/23/2021, 9:05 AM
sure Simon
I do not know if people would like it since if you are using suspend it implies it is an impure function. And may be it is not the best way to use function composition with side effect functions
for now I have just write my own
Ill think abou that
View count: 22