https://kotlinlang.org logo
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
  • k

    kyleg

    12/19/2019, 5:32 PM
    I am building an app maximizing my Arrow usage to try and learn how to use it. I start with an
    IO { File("/path/to…").walk()) }
    and apply IO transforms to the sequence to end up with an
    IO<Sequence<IO<Foo>>>
    and then use
    flatMap
    and
    sequence
    to transform it to
    IO<Sequence<Foo>>
    . When I
    unsafeRunSync
    the result, I get a
    StackOverflowError
    , presumably from the part where I “lift” the nested IO out of the Sequence (has to iterate over all the elements in the sequence I think). Given that you’re ideally going to have a single place at the “edge” to run the IO, is there a better way I should structure it? Assume I’m starting with
    IO<Sequence<IO<Foo>>>
    and can do whatever to it. Is
    myIO.unsafeRunSync().forEach { it.unsafeRunSync() }
    the way I should go about doing it at the edge? Basically run the top-level IO to get the
    Sequence
    and then start taking values, whcih are themselves
    IO
    , and run them? Here is a simplified version of what I have now:
    fun buildFoo(file: File): IO<String> = IO { "test" }
    val program: IO<Sequence<File>> = IO { File("/Users/kylegoetz/Desktop").walk() }
    val transformedProgram: IO<Sequence<IO<String>>> = program.map {
        it.map {
            buildFoo(it)
        }
    }
    val noNestedIO: IO<Sequence<String>> = transformedProgram.flatMap {
        it.filterNotNull().k().sequence(IO.applicative()).fix()
    }
    
    noNestedIO.unsafeRunSync() // StackOverflowError
    j
    r
    • 3
    • 39
  • j

    Jannis

    12/19/2019, 7:17 PM
    A solution is a lazy version of
    ap
    (it's actually solution to many many more problems 🙈 ) with that we would instantly return from
    traverse
    and execute/bind the
    IO
    as we go
    r
    • 2
    • 15
  • k

    kyleg

    12/19/2019, 7:24 PM
    not because it’s the practical thing to do, but because it gives me a reason to learn more about FP
    j
    j
    • 3
    • 5
  • j

    jimn

    12/19/2019, 8:04 PM
    does this syntactic sugar live in Arrow-kt by a named concept i can study up? it looks as close as i can make to the cat theory chalkboards lectures of f follows g
    operator fun <A, B, C> Function1<A, B>.times(r: Function1<B, C>): (A) -> C = { x: A -> x.let(this).let(r) }
    demonstrated below with the _***_'s
    val bb2ba: (ByteBuffer) -> ByteArray = { bb: ByteBuffer -> ByteArray(bb.remaining()).also { bb[it] } }
    val btoa: (ByteArray) -> String = { ba: ByteArray -> String(ba, Charsets.UTF_8) }
    val trim: (String)->String  = String::trim
    enum class TypeMemento(val bytes: Int?, val read: readfn, val write: writefn) { 
        txtInt(4, (bb2ba * btoa * trim * String::toInt), { a: ByteBuffer, b: Int? -> a.putInt(b ?: 0) } as writefn),
    j
    r
    • 3
    • 10
  • s

    Sagar Suri

    12/20/2019, 9:54 AM
    The new look of arrow-kt.io is amazing 🤩
    💯 20
    :arrow: 18
    😯 2
    r
    • 2
    • 2
  • r

    raulraja

    12/20/2019, 5:23 PM
    Excellent first issue for someone wanting to understand error handling in FP. Review and update the error handling tutorial to use friendlier models that are not war related. https://github.com/arrow-kt/arrow/issues/1873
    👍 1
    b
    a
    • 3
    • 4
  • s

    stojan

    12/22/2019, 1:15 PM
    anyone experienced
    arrow/core/Continuation
    java.lang.NoClassDefFoundError: arrow/core/Continuation
    in tests
    s
    • 2
    • 2
  • m

    Michael Marth

    12/22/2019, 5:08 PM
    Worked through https://www.pacoworks.com/2019/12/15/kotlin-coroutines-with-arrow-fx/ and tried to give it a shot on Android with Room (works great!) - however, I cannot get the
    Promise
    to mimic the view model lifecycle callback (as described at the end of the post):
    val endPromise: Promise<ForIO, Unit> = Promise.unsafeUncancelable(IO.async()).fix()
    simply does not compile. Same for
    endPromise.complete(Unit).unsafeRunAsync { }
    accordigly.
    fix()
    /
    unsafeRunAsync
    are simply not availble on the
    Promise
    instance. Any ideas?
    j
    • 2
    • 5
  • f

    Fudge

    12/22/2019, 8:13 PM
    Is there a benefit for using
    Option<>
    types over
    Nullable?
    types other than the syntactic difference?
    r
    • 2
    • 3
  • p

    pakoito

    12/23/2019, 3:10 PM
    You can define
    typealias Bla = suspend (In) -> Out
    m
    • 2
    • 1
  • s

    stojan

    12/23/2019, 6:40 PM
    what would be the way to log the exception (just log, do nothing to recover the failure) in case an
    IO
    fails?
    t
    p
    +2
    • 5
    • 16
  • e

    Egor Trutenko

    12/24/2019, 1:09 PM
    Hey guys. I was thinking, is there a point in adding something like http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Category.html to Arrow? I just had a case where I had to generate a free poset by hand to encode some business rules, and intuition tells me that I could derive a lot more from it, but I can't get my mind around it yet. Thoughts?
    j
    r
    • 3
    • 8
  • k

    kyleg

    12/24/2019, 5:47 PM
    IntelliJ warns me of an inappropriate blocking method call on
    ImageIO.read
    here. I understand it probably wants me to put this in a suspend fn and it’s just a linting thing. But since it’s in an
    IO.fx
    and has
    !bind
    wrapped around it, I should ignore this linting warning, right? That’s part of the point of IO and !effect, right?
    fun imageReader(file: File): IO<Either<Throwable, ByteArray>> = IO.fx {
        with(!effect { ImageIO.read(file) }) {
            val argbArray = getRGB(0,0, width, height,null,0, width)
            val buffer = java.nio.ByteBuffer.allocate(4*argbArray.size)
            argbArray.forEach { buffer.putInt(it) }
            buffer.flip()
            buffer.array().slice(0 until argbArray.size*4).toByteArray()
        }
    }.attempt()
    s
    r
    • 3
    • 5
  • k

    kyleg

    12/24/2019, 5:49 PM
    Or should I be shoving this !effect into some other thread/dispatcher/process like one might in Android with
    launch(<http://Dispatchers.IO|Dispatchers.IO>)
    or something? (This is a Kotlin command line program I’m working on)
    s
    s
    • 3
    • 6
  • j

    julian

    12/25/2019, 4:10 PM
    @marc0der Who do I talk to at Manning to suggest the time has come for a Kotlin version of Functional and Reactive Domain Modeling? I’m up to chapter 4 and neck-deep in trying to understand Scala implicits in order to in turn understand the code samples. A high price to pay for an Android developer whose interest is keenly in FP, definitely not Scala-FP. Implicits are easy to understand at a high level and in principle. But what a mess to understand when used.
    s
    r
    • 3
    • 19
  • s

    stojan

    12/26/2019, 11:23 AM
    just solved the Birthday Kata with Arrow, if anyone has the time to take a look, any feedback is appreciated, thanks -> https://github.com/LordRaydenMK/BirthdayKata
    ❤️ 5
    s
    j
    • 3
    • 23
  • t

    Tim Fennis

    12/27/2019, 3:50 PM
    The new arrow site is incredibly sexy, my compliments to the designer(s) ❤️
    ❤️ 8
    r
    r
    • 3
    • 3
  • u

    ursus

    12/29/2019, 3:17 AM
    What would be a good name for a union of Loading, Success, Error?
    r
    a
    s
    • 4
    • 11
  • m

    Michael Marth

    12/30/2019, 3:05 PM
    I want to execute a list of of
    IO
    actions all together with one call to
    unsafeRunSync
    . I know in Haskell there is
    sequence
    - is there a similar construct in Arrow?
    j
    a
    • 3
    • 7
  • m

    mattmoore

    01/01/2020, 3:04 AM
    I'm looking into combining Arrow (possibly Fx?) with JetBrains Exposed library. Any resources or best practices/recommendations around this? I've found this, but not sure what state it's currently in: https://github.com/codebandits/beak
    r
    j
    • 3
    • 6
  • m

    mattmoore

    01/01/2020, 3:23 AM
    I'm also trying to integrate with Ktor, but it seems a little difficult to get Ktor to play nicely with Arrow types. Fairly new to this though, so I might be missing something...
    r
    • 2
    • 7
  • r

    Razvan

    01/02/2020, 2:48 PM
    Thanks that worked…
    p
    • 2
    • 2
  • a

    Adam Daniel

    01/02/2020, 8:57 PM
    Hello, I am trying to compose my program using arrow-fx with suspend functions instead of IO. Is there a possiblity to bind() suspend functions in Either.fx block? Like this:
    object BusinessError
        object User
        object UserProfile
    
        suspend fun findUserByName(name : String) : Either<BusinessError, User> = TODO()
        suspend fun getUserProfile(user: User) : Either<BusinessError, UserProfile> = TODO()
    
        suspend fun getUserProfile(name : String) : Either<BusinessError, UserProfile> = Either.fx {
            val user = findUserByName(name).bind()
            getUserProfile(user).bind()
        }
    a
    j
    • 3
    • 10
  • c

    Christian Maus

    01/04/2020, 1:43 PM
    I’m struggling to understand how to replace Try with the suspending constructors of Either in the context of monad transformers. Can someone point out to me how to replace Try with Either.catch in my code?
    import arrow.core.Either
    import arrow.core.ForEither
    import arrow.core.Option
    import arrow.core.Try
    import arrow.fx.ForIO
    import <http://arrow.fx.IO|arrow.fx.IO>
    import <http://arrow.fx.extensions.io|arrow.fx.extensions.io>.applicative.applicative
    import arrow.mtl.EitherT
    import arrow.mtl.OptionT
    
    
    typealias IOResult = EitherT<ForIO, Throwable, OptionT<ForEither, Int>>
    val doesNotWork = IOResult.fromEither(IO.applicative(), Either.catch { Option.just(3) })
    val doesWork = IOResult.fromEither(IO.applicative(), Try { Option.just(3)}.toEither())
    r
    j
    • 3
    • 12
  • a

    abendt

    01/04/2020, 2:35 PM
    when using Kotlin Coroutines a
    suspend
    function should not use blocking operations. How is this in the context of arrow-fx and
    IO
    ? Is this a requirement here too or is
    suspend
    only used as a marker to tag functions for having sideeffects?
    a
    r
    • 3
    • 15
  • j

    jimn

    01/06/2020, 2:28 PM
    do i have this right?
    /** left identity */
    object `⟳` {
          operator fun <T> invoke(t: T) = { t: T -> t } 
    }
    
    /** left identity */
    val <T> T.`⟳` get() =   `⟳` ( this) 
    /**right identity*/
    val <T> T.`⟲` get() = { this }
    r
    • 2
    • 9
  • r

    rcd27

    01/07/2020, 7:26 AM
    Hi guys, Android dev with 5+ years of experience looking for a job (me). Why posting here? Because
    arrow-kt
    connects people who loves Functional Programming and I really wish to work with
    Arrow
    on project or on back-end Scala.
    s
    • 2
    • 1
  • s

    Scott Christopher

    01/07/2020, 9:11 AM
    Curious whether it would make sense or not to add type arguments of the typeclasses to their interface, e.g.
    interface Functor<F, A> {
      fun <B> Kind<F, A>.map(f: (A) -> B): Kind<F, B>
    }
    The reason I ask is that I went to update the
    Profunctor
    interface to extend
    Functor
    and provide the default implementation for
    map
    using
    rmap
    , though the only way I could make the types line up was to update
    Functor<F>
    to
    Functor<Kind<F, A>, B>
    like so:
    interface Profunctor<F, A, B> : Functor<Kind<F, A>, B> {
        fun <C, D> Kind2<F, A, B>.dimap(fl: (C) -> A, fr: (B) -> D): Kind2<F, C, D>
        fun <C> Kind2<F, A, B>.lmap(f: (C) -> A): Kind2<F, C, B> = dimap(f, ::identity)
        fun <C> Kind2<F, A, B>.rmap(f: (B) -> C): Kind2<F, A, C> = dimap(::identity, f)
        override fun <C> Kind<Kind<F, A>, B>.map(f: (B) -> C): Kind<Kind<F, A>, C> = rmap(f)
    }
    r
    j
    • 3
    • 6
  • k

    kyleg

    01/07/2020, 8:11 PM
    Is there any good document out there explaining why using something like
    Kind<F, A>
    is so helpful compared to
    F<A>
    (i.e. and e.g., not hard-coding that your return type is
    Option<A>
    )? I’m hoping there’s some blog out there showing a real-world reason someone chose to do this and how it benefited them. Is this just so you don’t have to refactor your function’s signatures from an
    Either<Throwable, A>
    into an
    Option<A>
    if you change your mind halfway through development, or is there something greater out there? It seems like tutorials are implying a connection to something like an
    interface
    in OOP (being able to write to a more generic “contract”), but I haven’t been working with FP long enough to grok the real-world benefits. Thanks.
    b
    a
    j
    • 4
    • 6
  • f

    Frank

    01/08/2020, 4:55 PM
    if I have a
    List<A>
    and a function
    A -> Option<B>
    , is there an operator, or series of operators, that would iterate over the list, applying the function, and return the first
    Option<B>
    that is a
    Some<B>
    , and if none do, returns
    None
    ? Similar to a
    findFirst
    but runs a computation
    j
    • 2
    • 2
Powered by Linen
Title
f

Frank

01/08/2020, 4:55 PM
if I have a
List<A>
and a function
A -> Option<B>
, is there an operator, or series of operators, that would iterate over the list, applying the function, and return the first
Option<B>
that is a
Some<B>
, and if none do, returns
None
? Similar to a
findFirst
but runs a computation
j

Jannis

01/08/2020, 5:07 PM
There are multiple ways to do this: First the most basic one is:
filterMap(f).firstOption()
using
filterMap
from
FunctorFilter
and
firstOption
from
Foldable
. (If you do the same with
asSequence().filterMap(f).firstOption()
it'll also be lazy ^^). When this pr (https://github.com/arrow-kt/arrow/pull/1897) is merged you can also do
map(f).asum(Option.alternative(), ListK.foldable())
asum
basically tries every element and short-circuits on success (which is similar to
traverse
which short-circuits on failure). I'd suggest doing the
asSequence().filterMap(f).firstOption()
because it won't apply the function unnecessarily and because it is available now ^^.
🔝 1
f

Frank

01/08/2020, 5:44 PM
Oh that’s great! thanks for the reply! I’ll try it out!
View count: 3