#BabelOfCode 2024
Week 11, Puzzle 17
Language: Idris

PREV WK: mastodon.social/@mcc/114582208…
NEXT WK: mastodon.social/@mcc/117661433…
PUZZLE TEXT: adventofcode.com/2024/day/17

Now getting extreme with "puzzles out of order". Here's the problem. The AOC author *really* likes puzzles involving 2D arrays. It makes sense. They're easy to visualize as either ASCII art or PNGs. They're a rich space for "simulations". But some languages are better at them than others.

So for Idris week, I pick the "build a CPU" puzzle.


#BabelOfCode 2024
Week 12, Puzzle 12
Language: Zig

PREV WEEK: mastodon.social/@mcc/117436256…
RULES: mastodon.social/@mcc/113676228…
PUZZLE TEXT: adventofcode.com/2024/day/12

I've been needing to learn this one.

Zig was first introduced to me, when I was writing video games, as a good new language for video games. I kept near-missing it. Back when it first debuted, I was in a phase of being heavily into Nim; when it hit maturity, I was starting to get heavily into Rust.

Now it's a candidate for replacing Rust.


This entry was edited (Sunday, November 22, 2026, 8:47 PM)
in reply to mcc

Idris is "Haskell, but more so". Haskell is "ML, but more so". I have always liked ML. I have never liked Haskell (although when I tried it again for this thread series, I enjoyed it more than I expected). I have always suspected I might like Idris more than Haskell. Maybe the awkward concepts in Haskell aren't *awkward* just *incomplete*. Maybe another language could complete them.

Conveniently, Idris installs itself through the Haskell package manager, which I already installed for week 7!

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Inconveniently the Haskell package manager doesn't fricking work.

What… I don't understand what this very long error message is telling me. Do I need to upgrade Cabal? Do I need to downgrade Cabal? Is some existing package I have selected in a version incompatible with Idris? I can literally blow away my entire set of installed Haskell packages, I don't mind. Would that help? 🙁

EDIT: A six year old Google Groups comment reveals the secret is to pass cabal the flag "--allow-newer". Terrifying

This entry was edited (Tuesday, October 13, 2026, 11:49 PM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Cont'd
- Passing --allow-newer fails *worse*—well, I turned the safety off
- I read the tutorial closer. It links a github
- The github is archived.
- I back ALL the way out. Instead of searching "idris tutorial" I go to the Idris home page. I then discover
- I have been looking at the Idris 1 tutorial. Idris 1 is discontinued. New thing is Idris 2.
- Idris has a totally different tutorial and is now deployed via Racket instead of Haskell (?!??)
- I have been, apparently, barking up a dead tree.
This entry was edited (Thursday, October 15, 2026, 2:42 PM)
in reply to LR

@lritter yeah if you want to get started with idris, please ask for help, it will save you a lot of time.

i usually recommend github.com/stefan-hoeck/idris2… for installing idris 2. and the default backend is chez rather than racket.

@LR
in reply to mcc

@dysfun @lritter We have a zulip! idris-lang.zulipchat.com/ Let me know if you have any questions as well. The language is much less polished than I want but we're working on it to make it better every day. All feedback is welcome

Edit: I'm working on tech debt on the idris2's LSP implementation as we speak!
Edit2: I'm UTC+0 (+1 soon)

This entry was edited (Wednesday, October 14, 2026, 3:40 PM)
in reply to Andre Videla

@Andrev no, it's a wonderful property, in theory.

but there's so much that would need to be improved to make it something anyone less nerdy than us would use, and i don't think it's realistic to think it will ever get there. so i worry about what extended honest feedback would do for your mental health.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

So.

I install Racket. Wow! Racket takes up a lot of space! I guess I'll need this for week 14 anyway.

I install "pack", Idris's dedicated package manager. I guess I don't get to be happy Idris uses an existing package manager anymore. Installation for the Idris package manager is "curl to bash". The bash script clones a git repo. There is weeping and gnashing of teeth. There is no way I will remember to uninstall this thing or remove it from my bashrc files when this project's done. Whatever.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Anyway! Idris! I'm in!

Idris is a "dependent types" language. "Dependent types" are the thing your favorite language doesn't have that prevents you from having that feature you wished it had but it doesn't. A running gag in Rust is every desirable but missing feature would be possible with dependent types. DT means a type can contain a value, or do ops on values, for example a function that adds an array of length N to an array of length M and produces an array M+N. Like Ada, but… … … better?

in reply to mcc

For some reason Idris has two tutorials.

idris2.readthedocs.io/en/lates…
idris-community.github.io/idri…

Reading how they describe their types, I wonder if the CPU emulator puzzle was the wrong choice for this language. Something with arrays might've better exercised Idris' capabilities?

First thing that catches my eye: it has an "infix" sugar like ML. But then they say:

"Functions, data constructors, and type constructors may all be given infix operators as names."

TYPE CONSTRUCTORS MAY BE INFIX

HECK YES

This entry was edited (Thursday, October 15, 2026, 2:43 PM)
in reply to mcc

Unsorted thoughts

"Holes are useful." is a funny sentence to see in a manual

"where" and "let" seem redundant

> Nested record fields can be accessed using the dot notation:
>
> x.a.b.c
> map (.a.b.c) xs

…Haha heck nice, that was the feature I was proudest of in Emily

"multiplicity 0" (calculated/erased at compile time) and "multiplicity 1" (linear typing) sound like things I VERY MUCH want in a programming language, though the ergonomics around it are a little alien to me, a C/Rust girl

in reply to mcc

Okay important question

I have a vague sense Haskell has "monads" and Idris has "applicatives". Idris in fact seems to have both— idris2.readthedocs.io/en/lates…

If I say "do" I've made a monad and if I say "[| … |]" (ugh, ocaml at its worst) that's an applicative. Difference isn't clear. If I just write monads and ignore [||] in my learning-Idris program am I Missing Out?

I still don't know what an Effect is. I thought it was the Effect Monad but the Idris manual talks like applicatives are Effects.

in reply to cassie

@porglezomp @prozacchiwawa imagine i'm writing an Idris program specifically to learn about the differences between haskell-like FP and Idris-like FP. it seems like to get the most value out of this if i can understand when applicatives are valuable and use them under that circumstance. what "line" would you say is the one that if i cross it [in my design] i have just hit the point knowing "oh, that was an applicative" was useful?
in reply to Caden

@tarix29 @prozacchiwawa oh right I forgot that eventually got fixed like a decade ago: wiki.haskell.org/index.php?tit…

They didn’t fix the duplicated incompatible names though, so it’s still idiomatic to use different names for the same operation depending on what typeclass you’re working with. In Idris all the operations just get one name.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Okay so the important things seem to be this comment

social.treehouse.systems/@dysf…

the second screenshot (the terminal shot) attached to this post

and this comment

mastodon.social/@porglezomp/11…

I still don't understand it, but I think I'm closer to understanding it than I have been ever in the last 25 years. Just gotta think about those type signatures. And in the meantime I don't *have* to understand it, I can just use do notation and worry later about which Math Things my code corresponds to.


haskell and idris both have both

your three fundamental typeclasses for effectful stuff are functor, applicative and monad.

functor: map (<$>)
applicative: apply (<*>)
monad: bind (>>=).

the those weird brackets are called idiom brackets and tbh i'm a bit hazy about how they work but i think they try to DWIM across the above . i just do it the old/haskell way.

effect, well you can think of it as a 0-ary function. i.e. it's hidden behind a lambda and not actually doing anything yet (use map and apply and bind to sequence them). so the top level of your program turns into a 0-ary function after sequencing.


This entry was edited (Wednesday, October 14, 2026, 8:19 PM)
in reply to mcc

I used to be afraid of functional programming languages like Haskell and erlang because I thought they were logic solvers like prolog, and I was not able to wrap my head around prolog. But no, erlang just turned out to be just a different way to express imperatives. Then I was using prolog to solve the "murdle" logic game puzzles for awhile, so I'm less scared of it than I was, but I still don't think I could make a web application with it.
in reply to Michelle Hughes

@MegaMichelle idris is the one programming language with a theory of dependent types which can be used in very interesting ways and the language comes from an academic community very close to interactive theorem provers although the proof community will tell you its theory isn't quite sound
in reply to mcc

Among the things not mentioned in either Idris tutorial

- What file extension is used for Idris files? (it's .idr)

- How do you execute an idris file?

Running idris2 puts you at a REPL. Running "idris2 src/puzzle.idr" churns a long time, creates a series of utterly baffling files in a build/ subdirectory, then drops you at the same repl. "-c" does this then quits; but it still does nothing useful.

One tutorial implies "pack -o hello exec src/puzzle.idr" will do something; this hangs forever

in reply to mcc

I understand true LISP heads are comfortable just spending all their time in a REPL forever. I am not a true LISP head. I'm an ocaml poser.

I *think* the mysterious "pack" command, while hanging, created in the mysterious "build" subdirectory a "hello.rkt" file that wouldn't have been there otherwise. I remember someone saying idris works by transpiling itself to a "backend" lang, so maybe I'm supposed to figure out the non-hanging args to "pack", transpile, then execute the rkt file in racket.

in reply to mcc

*Rubbing eyes* okay, so

idris2's command line --help lists a "-o <file>" flag, which "specifies output file". Output file for what? Apparently this actually means "build an executable, put it in ./build/exec [path non-negotiable], and name it <file>".

I run this. I run it in `time`. It does create a runnable Linux executable.

It takes it one minute and fifty-three seconds to compile the program:

main : IO ()
main = putStrLn "Help"

During which time I sincerely could not tell if it had hung

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

So after a brief conversation with Idris2 maintainers

- Idris can run on top of either "Racket" or "Chez". I went with Racket because I thought it was the fast one. This is no longer true. The maintainers expect Chez to be a little faster. In fact it's hundreds of times faster. This surprises the maintainers.

- Additionally, in Debian, Chez takes up 10% the disk space of Racket.

After what I'd consider a somewhat unfriendly uninstall procedure, I re-install idris2, atop Chez.

It doesn't work

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

After some poking, it turns out that installing Idris2 in Racket mode, then uninstalling with the given instructions, then re-installing in Chez mode, leaves the system in an inconsistent state where it sometimes uses Racket and sometimes doesn't work at all. I need to stress I have various community members and maintainers in my mentions trying to help me and they're being very nice. They give me hand-surgery to perform on a TOML file. It ixes it. Compiling takes 1.4s instead of over 2 minutes.
in reply to mcc

Furthermore, it appears that in addition to the two tutorials I mention above, the ones linked from the regular Idris website, there is a third, secret tutorial, and this one explains how to actually execute a piece of code, explains why readline isn't working right in the idris2 repl, etc. codeberg.org/jjl/tutorials/src…

I guess I can move on now. Hopefully there aren't more nasty surprises lurking in my toml configuration file (presumably lying in wait to blow up if I attempt to configure an LSP).

in reply to mcc

So Sublime Text doesn't have an Idris LSP package-- only an Idris syntax highlighting package.

But it turns out if I `pack install-app idris2-lsp, then in Sublime go to Package Settings -> LSP -> Server Configurations

{
"idris2-lsp": {
"enabled": true,
"command": ["/home/mcc/.local/bin/idris2-lsp"], // Update the PATH
"selector": "source.idris"
}
}

It just like… magically works. I have type-on-hover now. As long as I create a .lidr file with idris2 --init.

in reply to mcc

27 hours after beginning this thread, I successfully write my first line of Idris code. (It's opts <- getArgs). Now I just need to figure out how to get an item out of a list.

There's a better looking options parser in the standard "contrib" library, but I can't figure out how to get it out. I decide to dip a toe in the idris Zulip.

idris-lang.zulipchat.com/#narr…

Among the deficiencies in the tutorials: They describe how to find third party libraries, but not how/where the stdlib is used/documented…

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Tried to write my second line of Idris. Disaster.

It's highlighting "=>" and giving the error "Expected '=>'". Don't know how to proceed.

Part of the problem is Idris has elaborately documented its upgrades from Haskell, but the tutorials kinda handwave the basic stuff. In ML I'd expect to deconstruct a one-element list like [x] or like x::nil. In Idris I… I don't know. Maybe if I sleep and reread all the docs.

Also, I'm missing how I, inside of a do, "abort the do block/program with error"

in reply to ∴ esoterik ∴

The media in this post is not displayed to visitors. To view it, please go to the original post.

@d6 hm. it doesn't like that either and for the same reason.

is the real problem that getArgs is inside an io monad and i have to unwrap it?

actually i think this must be a problem with my actual syntax because if I change "getArgs" to "getArg" I get the same error. Implying the compiler is bailing out so early it isn't checking names.

in reply to mcc

I don't understand why that is the error message and I don't know what the "exit program" function is. However: your pattern is fine; idris understands `[x]` as a pattern in `case`. But you do need to bind `getArgs` outside the `case` (b/c getArgs is in the IO monad), eg. this works:

import System

main : IO ()
main = do
args <- getArgs
case args of
[x] => printLn x
_ => putStrLn "nope"

This entry was edited (Thursday, October 15, 2026, 4:01 AM)
in reply to rntz

looks like exitWith or die will exit: idris-lang.org/Idris2/base/doc…

eg this will print its "first" command-line argument (the 1st element of getArgs is the command itself, so the 1st "argument" is actually the 2nd element).

main : IO ()
main = do
args <- getArgs
arg <- case args of
[_, x] => pure x
_ => die "wrong number of arguments"
putStrLn arg

in reply to mcc

Without pure, the two case-branches have different types. `x` is a String, but `die "..."` is an IO computation. `pure x` puts x into the IO monad, so both branches can have the same type, IO String.

for comparison, consider an expression like

if test() then 2 else "wub"

this seems ill-typed, because 2 and "wub" have different types. in Idris, IO-computations have different type from non-IO things, and a String is not automatically convertible to an IO String.

This entry was edited (Thursday, October 15, 2026, 6:01 AM)
in reply to mcc

You can freely move around expression that you write with `let`, you cannot freely move around expressions that you write with `<-` because that is doing a monad bind. Notably in a bind, the type of the variable is different from the type of the expression you’re binding from.

`do x <- getArgs; f x` is syntax sugar for `getArgs >>= \x -> f x`, which maybe helps you carefully work through all the types manually?

in reply to mcc

To make a (very rough!) analogy to an imperative language, `args <- getArgs` is like calling a function, `getArgs` by itself is like naming the function itself.

So the first example is like writing

```rust
let args = getArgs();
match args {
...
}
```

While the second example is like writing

```rust
match getArgs {
...
}
```

which fails because you can't pattern-match on a function

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

I am struggling with making sense of this language's standard library.

The attached code works. It takes a filepath as argument and prints the contents.

But

- If instead of System.File.ReadWrite I use Control.App.FileIO, nine kinds of hell erupt

- I can't figure out how to turn the FileError (Left x)idris-lang.org/Idris2/base/doc… into… ANYTHING. I can't get that "Show FileError" to do anything in the repl. "import" in the repl fails

- In general, I can't search prelude/base for a symbol by name?

This entry was edited (Thursday, October 15, 2026, 9:57 PM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Moreover, I don't want to put the file contents into a string. I want to parse them in a very simple way— verify text "Register A:" at start of line one, parse comma-separated list, move on to line two etc. I don't know how to get "here's a list of string ops" "here's a list of file ops". I find this idris-community.github.io/idri… it's explaining concepts of applicatives and I want to know what operations exist for simple parsing of strings. I don't know what "go" does or where to look it up.
in reply to Andre Videla

Just realised you might want to access the list of arguments, and also enjoy string interpolation:
import System<br><br>main : IO ()<br>main = do<br>  args <- getArgs<br>  case args of<br>       [_, arg1] => putStrLn "oneArgument"<br>       [_, arg1, arg2] => do<br>         putStrLn "twoAguments:"<br>         putStrLn arg1<br>         putStrLn arg2<br>       args' => putStrLn "\{show (length args `minus` 1)} arguments"<br>

careful, if you write length args - 1 this won't work because length returns a Nat which doesn't support a - operator because it doesn't have values below 0 because it's a "natural number"
in reply to mcc

OK so this is great but also, it speaks to what I perceive as a "missing low-end" in the Idris docs— like, if I want a high-end library for doing command-line argument parsing I can find that in seconds in the well-curated third-party libraries list and install it via Pack, but if I want to know the name, package and type signature of the "getArgs" function in the standard library this is shockingly much harder.

Maybe :doc will help some now that I know about it.

mastodon.social/@dysfun@treeho…


i believe this is the currently favoured parsing library github.com/stefan-hoeck/idris2…

in reply to mcc

Now, note, even I think I'm "doing this wrong"— what I would have *wanted* to do is put that big do block inside of a helper function that returns a string, and then have my actual app processing be a pure function that takes the string returned as and passes that through lines ("lines" splits a string on newline) and then does all the other operating. Maybe if I do that it will magically go away? Also I don't know what the "pure"s do and included them bc I copypasted from someone else's code.
in reply to mcc

A big problem I'm having, and I can't tell if this is a problem with Sublime Text or a problem with idris, is that if there is even on error anywhere in the program the LSP will not do type inference on anything in the program at all. Which makes sense if you think about it because if there's an error it can't infer types. But also kind of HURTS, A LOT because normally the way I'd resolve a typing error is by mousing over each variable in the expression to see what its type is and if I expect it
in reply to mcc

Okay so I *think* I managed to fix the "monad" errors in this, and I'm proud of that

gist.github.com/mcclure/8c6baa…

But I am utterly defeated by the error "Mismatch between: AsList (strCons ?_ ?str) and List1 String." (a later error gives this as "Mismatch between: List ?a and List1 String."). I thought ? meant there was a hole. But I didn't write any holes

Hey is there a builtin "dispose" function in Idris. Like _ -> () if I want to end my do block with a value but I'm not ready to do with anything

in reply to mcc

I think casing as [x, y, z] desugars to (x :: y :: z :: []) and :: is overloaded so there's three separate errors telling you how each of the three :: fails to type check
the middle one looks the most sensible since you're working with Lists and not any of this aslist or stream stuff
I looked up the type of split and it returns a List1 a which has constructor (::😀 : a -> List a -> List1a, so in that case expression you would watch to match on the pattern (_ ::: [_, i_string])
in reply to njplschy

@ionchy

Error: While processing right hand side of main. While processing right hand
side of main,interpret_register. Undefined name :::.

src.puzzle:26:7--26:10
24 | let words = split (== ' ') line in -- Split on spaces, throw away first two cells
25 | case words of
26 | _ ::: [_, i_string] => case parseInteger i_string of
^^^
Did you mean: ::?

And no, adding parens does nothing

in reply to mcc

Ok sothe vague error has mostly to do with one thing, and that is overloaded strings. Essentially the first error is telling you "I have trouble deciding if this is something looking like a string, or a List1 String, either way this has the wrong type". However, Idris doesn't know *what* kind of string you're using, so you get *that*

The main problem is split returns a List1, not a List, so you can't pattern match on it like a List. Instead of "[_, _, i_string]", try "_ ::: [_, i_string]"

This entry was edited (Friday, October 16, 2026, 8:19 AM)
in reply to mcc

*Rubbing eyes* okay. Okay.

So what I wanted is a List String. "split", the string function, returns a List1 String. I assumed the 1 was "noise". Using this language, I find a lot of "noise" in the messages and docs.

No, it was very important.

So to construct or deconstruct a list in a post-LISP FP language, you use :: , right? Everyone knows that. Right before I went to bed last night, I got a message saying I needed to use ::: , not :: . I literally assumed this was wrong. No, It was right.

in reply to mcc

What I *should* have done, when the split doc said List1, is look up what that was. I mean, I did, and it said a List1 is just a List with at least one element. That sounded normal to me. Idris is all about the dependent types thing, right? So logically this should just be a List with some constraint on it. I assumed it would work like a List.

No, it's different. To interact with it you have to import Data.List1, then use ::: instead of :: .The [a,b] sugar will not work.

I… hm. Hrm. Hmrmrmhf

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

One thing that concerns me: What if, for some reason I can't currently guess, I needed a List which is dependently typed to have at least 26 elements? Would I define a List26, and assign it :::: , and hope it doesn't conflict with someone else's List4 which also defined a :::: ? Starts feeling weird

Anyway, now onto the next problem: DYING IS A SIDE EFFECT. WHAT DO YOU MEAN DYING IS A SIDE EFFECT. LIKE OK IT IS BUT I SHOULD BE ABLE TO DIE ANYTIME I WANT. I'M NOT ALLOWED TO DIE WITHOUT A MONAD??

in reply to Jonathan Lamothe

@me Is there?

Searching:

idris2docs.sinyax.net/

The only thing I think I find is idris2docs.sinyax.net/data/idr… , which is based on idris2docs.sinyax.net/data/bas… .

App means applicatives are in effect, right? I'm in the … HasErr… applicative? Which OK, I think means I don't need a monad. But does that mean I have to declare all my functions all thew way up as HasErr? Will the IO monad and the HasErr applicative fight when they come into contact?

mcc reshared this.

in reply to mcc

So my understanding of haskell "monads" is that they're really just very fancy syntactic sugar for wrapping each line of code in some kind of transformation. Usually the monad is "IO" because the transformation is a magic "wait for external input".

It seems like I ought to be able to use a monad to do wrapping similar to Rust Result<>?, and not have to go all the way to IO, and still have a pure function. Someone said Either is a monad.

Someone says, "you can use error"—EDIT: No,that's Haskell


@me Is there?

Searching:

idris2docs.sinyax.net/

The only thing I think I find is idris2docs.sinyax.net/data/idr… , which is based on idris2docs.sinyax.net/data/bas… .

App means applicatives are in effect, right? I'm in the … HasErr… applicative? Which OK, I think means I don't need a monad. But does that mean I have to declare all my functions all thew way up as HasErr? Will the IO monad and the HasErr applicative fight when they come into contact?


This entry was edited (Friday, October 16, 2026, 6:45 PM)

prozacchiwawa reshared this.

in reply to erincandescent ⎔

It seems reasonable to me, and also very in line with the Rust design philosophy to figure that exceptional-case handling is so critical and unavoidable that building in low-level primitives for making it very easy to use *just this monad* and ignoring all other monads would be worth it. In fact, my sincere belief about Rust is that they should have not included Option at all and defined Option<T> as Result<T, ()>. They should have made this even simpler.
This entry was edited (Friday, October 16, 2026, 4:41 PM)
in reply to mcc

it's not so much that you can't really express them in Rust, it's that you can't be generic over them.

A monad is conceptually just a collection Foo<T> that matches the pattern of Option<T>::and_then, Vec<T>::flat_map, et al.

Haskell calls this method "bind". "Do notation" is just syntactic sugar for wrapping an expression in this method.

Rust can't express a Monad trait (as would be required for Do notation) because you can't express a trait that's generic over type parameters

in reply to mcc

error is an escape mechanism in Haskell that lets you throw an error even in pure (non-monadic) code. It would be convenient for what you are doing but it is frowned upon as “the wrong way to do things” (and for large programs and libraries it does indeed have problems) compared to learning to do everything with monads.

I don’t think Idris has error. It might have some other escape hatch like it though.

in reply to mcc

almost certainly it’s also a Monad? on phone so it’s hard for me to check rn…

Every Monad is an Applicative but not always vice-versa but it would be weird if Control.App.Error wasn’t a monad.

EDIT: Nope I think I’m wrong here. Not even sure that Control.App is about applicatives.

EDIT2: edit was wrong. Control.App.App is a monad (Control.App.Error isn't). but also it seems kinda complicated. I am not familiar with this part of Idris and it doesn't look like anything I know from Haskell.

This entry was edited (Friday, October 16, 2026, 4:59 PM)
in reply to mcc

Okay. So. The consensus from Idris users is to manually bubble the errors up using Either, like I'm a barbaric Rust user or something. I hit several problems.

gist.github.com/mcclure/a7498d…

1. Either and Maybe are monads. I've been told this since 2010. That implies I should be able to "do" them. I should have some way of rigging stuff so that, when a operation fails, "aborting" it like ? in Rust. Instead like chaining case statements like I'm a barbaric Ocaml user. Am I missing something?

(CONT'D)

in reply to mcc

2. It reeeeeallly bothers me that I'm using Either for error handling because it is not semantic. I'd like success to be Ok and failure to be Err. If I kept using Idris, how hard would it be for me to make an interchangeable Result version of Either with different names?

3. My code used a `map`. Therefore in order to bubble up errors, I need a way to "terminate" a map early. It turns out this exists and it's called "traverse". It furthermore turns out TRAVERSE TREATS LEFT AS ERROR

(CONT'D)

This entry was edited (Friday, October 16, 2026, 7:25 PM)

prozacchiwawa reshared this.

in reply to mcc

AND RIGHT AS SUCCESS. SO ONE (1) FUNCTION SWAPS FAILURE/SUCCESS BETWEEN LEFT AND RIGHT. I'm not asking for help here I'm just annoyed

4. Here's the point I actually need help: As you can see from "z_error.txt" in the above-linked gist, traverse can't operate on a List1.

…what?!

…what's even the point of higher-order functions over interfaces¹ then 🙁 🙁 🙁

I'm stuck. What should I do here? Write a function to convert List1 to List? List1 *is* a superset of List…

¹ "Typeclasses"

in reply to mcc

I do not miss arguing about Either for result representation but the Left x | Right x thing was always dumb. I can't think of any case where those are helpful names given implementations people would assume for various monadic operators as if math was the only clarification necessary to understand which thing was success and which was then error. Renaming these to Result like a civilized programmer is step one.
in reply to mcc

Answers to above questions

2. It turns out in Idris Left semantically means `Error` and Right semantically means `Ok`. Every standard library function follows this convention.

3. See 2

1. Just `do` when the return type is Either and any <- that attempts to assign Left auto-aborts. Like every line has an implicit ?. Awkward compared to ?, but better than nothing.

4. The actual error was ") in wrong place"— hard for any compiler to explain. Correct ) gives better error. Also: Data.List1.forget

in reply to _Έλλεν Εμίλια Ά. Arson Τζαϊλου

@fogti One output I'm getting from this conversation is that Rust has *exactly* two monads, Option and Result. Of these, Option is right-wing

doc.rust-lang.org/std/option/e…

and Result is left-wing

doc.rust-lang.org/std/result/e…

This only affirms my position that Option was a mistake and should be purged from the language in favor of Result<T, ()>.

in reply to mcc

Idris question

Does this language have a "map_left" or "map_right". Like Rust map/map_err ( idris2docs.sinyax.net/data/bas… ). I want to do a transformation on a Either, but I want to apply the transformation iff it is Right. I think I could write this myself if I had the mastery required to do… the things I'm already failing at. I notice there's an "eitherMapFusion" idris2docs.sinyax.net/data/bas… with no human-readable documentation and a baffling type. idris2docs.sinyax.net/data/bas…

in reply to mcc

adsfkjdsglkjfdgljag

github.com/mcclure/aoc2024/blo…

After *three* days, I have written a 65-line program that parses a very simple text file in a very simple way in Idris, which is the *prerequisite* to *starting* the puzzle I was hoping to finish within the week. And I was only able to achieve this much through massive personalized help. I will now time myself trying to write an equivalent program in Perl:

This entry was edited (Friday, October 16, 2026, 9:55 PM)
in reply to mcc

perl -e 'open(FH, $ARGV[0]) or die "No file"; ($a,$b,$c) = map {(chomp && scalar(/^[^ ]+ [^ ]+ (\d+)/ or die "Invalid register: $_"), $1)[1]} (scalar <FH>, scalar <FH>, scalar <FH>); <FH>; $program = <FH>; chomp $program; @program = split(/,/,$program); undef $program; close(FH); print "$a, $b, $c, program length " . +@program . "\n"' data/sample-4,6,3,5,6,3,5,2,1,0.txt

That took 12 minutes. 3 minutes to write the program and 8 minutes to debug it (It didn't work because I forgot "scalar".)

in reply to mcc

Now, a thing of note— I'm not coming in Idris "the expected way". The expected way would probably be to read through both those tutorials fully, The Conor McBride lecture notes on applicative programming, spend lots of time in the repl making sure I fully understand the Concepts, and then probably use a combinator parser library out of the Idris libraries list instead of hacking it with split(" ") and split (","). Probably it's unusual to just roll up to the compiler and go "I'MA DO TEXT IO NOW"
in reply to mcc

Hey question, does Idris have an equivalent of Ocaml |>

(I think this was "@@" in SML/NJ? And possibly $ in Haskell?)

EDIT: Yes… ha ha ha… yes! social.treehouse.systems/@dysf…

EDIT 2: In all the programming languages we write myself I just use ":" for this. It's that important to me. Nobody else I talk to ever seems to think this is good syntax

EDIT 3: Wait it isn't working

EDIT 4: Oh wait I asked the wrong question to start with. It's <| not |>


yes, it's called |> and it's imported by default

This entry was edited (Saturday, October 17, 2026, 5:07 PM)
in reply to mcc

You know you're using a functional programming language when you read through a module documentation containing about fifty functions trying to find the one that lets you look up a list member by index, and do not find it

idris2docs.sinyax.net/data/bas…

(I found two functions for getting the list index given a value, but did not find the function for getting a value given a list index. Not sure if my eyes glazed past it or if it's somewhere surprising in the Prelude)

EDIT: I think it's "index"

This entry was edited (Saturday, October 17, 2026, 5:32 PM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Update NOPE I did not in fact find the "index into a list" function. Because the index into a list function only exists if you can provide a proof that the index is less than the length of the list. Wait, but I don't know the length of the list? I was hoping the standard library would take care of that for me.

Experimentally, I try calling the inBounds function. It… something weird happens. It returns a "dec". Frustratingly, one of the types that isn't linked to its definition in the docs (1/2)

in reply to _Έλλεν Εμίλια Ά. Arson Τζαϊλου

The media in this post is not displayed to visitors. To view it, please go to the original post.

@fogti natToFin returns a Dec. but if I knew what to do with a Dec I could use inBounds mastodon.social/@mcc/117457579…


@amy I have two tutorials open and neither appear to explain indexing into a list. What would you recommend I read if I need to understand what to do with a Dec ? Because I tried what you said with an "if" and it did not work.

files.mastodon.social/media_at…


in reply to mcc

But per :doc it appears to be a predicate function. I *think* I don't call inBounds, I think I somehow *define* inBounds.

I think my options are:

1. Ignore "index"; write my own index that manually skims the list & returns an Either

2. Convert my list to a Vector, somehow, with its length as a generic parameter, somehow, and then when reading from the list test if my index (input from file; out of my control) is less than that generic-parameter length.

2 sounds better, but harder *_*

(2/2)

in reply to Amélia Liao 🍊😈

The media in this post is not displayed to visitors. To view it, please go to the original post.

@amy I have two tutorials open and neither appear to explain indexing into a list. What would you recommend I read if I need to understand what to do with a Dec ? Because I tried what you said with an "if" and it did not work.

files.mastodon.social/media_at…

in reply to mcc

@zmz @amy

step : Cpu -> IO Cpu
step cpu =
let (NewCpu ip reg prog) = cpu in
case inBounds (ip+1) prog of
Yes =>
^^^ error here ^^^
let opcode = index ip prog in
let operand = index (ip+1) prog in
putStrLn (show opcode)
No =>
die "Nope"

Error: When unifying:
?prop -> Dec ?prop
and:
Dec (InBounds (plus ?_ 1) ?_)
Mismatch between: ?prop -> Dec ?prop and Dec (InBounds (plus ?_ 1) ?_).

I do not understand a single error message in this language 🙁

in reply to Amélia Liao 🍊😈

okay. I see now. I was misreading the doc. Sorry, my head is swimming at this point and I'm missing obvious things.

The argument is given as a "Prop". Is this a value which means anything at runtime or is it like… I guess what I'd call a "phantom" in another language? Is there a reason to do anything other than _ it

EDIT: functional.cafe/@prozacchiwawa… seems to imply it's a phantom


@zmz @amy

No means: at the type level the thing you asked for couldn't be proven, so here's a function yielding Void that you can use with absurd or impossible to complete the proof.


This entry was edited (Saturday, October 17, 2026, 6:21 PM)
in reply to mcc

I mean, prop is just the name of the parameter to Dec. It could be an arbitrary type, e.g. the (Dec Nat) (Yes 123); here, you are deciding InBounds (ip + 1) prog. Ideally the auto parameter to index will pick it up automatically, in which case it can be _, but otherwise you might need to give it explicitly. You don't have anything to contradict the No case, so that can be ignored.
This entry was edited (Saturday, October 17, 2026, 6:41 PM)
in reply to prozacchiwawa

@prozacchiwawa @zmz @amy I see.

In my case, this is a legitimate error at runtime. I take input from a file which contains a list of numbers as well as indices into numbers. I can't know if an index is wrong at type time (unless I convert the list of numbers to a Vec, which I will probably try in the next step).

mastodon.social/@mcc/117457617…


@zmz @amy

step : Cpu -> IO Cpu
step cpu =
let (NewCpu ip reg prog) = cpu in
case inBounds (ip+1) prog of
Yes =>
^^^ error here ^^^
let opcode = index ip prog in
let operand = index (ip+1) prog in
putStrLn (show opcode)
No =>
die "Nope"

Error: When unifying:
?prop -> Dec ?prop
and:
Dec (InBounds (plus ?_ 1) ?_)
Mismatch between: ?prop -> Dec ?prop and Dec (InBounds (plus ?_ 1) ?_).

I do not understand a single error message in this language 🙁


in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

A proof that the natural (ip+1) is in bounds for array a is not a proof that the natural (ip) is in bounds for array a.

🙁

🙁

🙁 🙁 🙁

EDIT: [sad rageface ok face] ok tiny.tilde.website/@crazazy/11…


IIRC since you have a proof of `InBounds (ip + 1) prog` which normalizes to `InBounds (S ip) prog` you can deconstruct `Yes _` into `Yes (InLater prf)` and use `index ip prog {prf = prf}` in the body

This entry was edited (Saturday, October 17, 2026, 8:12 PM)

prozacchiwawa reshared this.

in reply to mcc

I'm really struggling with my docs for this language being two "tutorials" I'm juggling constantly.

I have a

case operand of
0 => 0
1 => 1
2 => 2
3 => 3
...

I would like this to be

case operand of
0 | 1 | 2 | 3 => operand
...

neither | nor repeating => is allowed here. Both tutorials skim the definition of a "pattern".

Is there like a … language spec I could be reading here to get *exact* syntax? A BNF? Maybe the source is just readable. Should I read the source?

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

I don't know Idris 2 but googled a bit and maybe this could be closer to what you want? Might be possible for your use case but I am not sure. idris2.readthedocs.io/en/lates… But since you know OCaml, maybe you discarded that idea already
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Okay so I'm probably sounding like a broken record at this point but.

I want to xor two numbers. I find an "xor" in Data.Bits.

idris2docs.sinyax.net/data/bas…

Doc says xor is "Fixity Declaration: infixl operator, level 6". I guess that means it's an infix operator. Wrong? 📎1

EDIT: Or right?? uh social.treehouse.systems/@dysf…

*A frustration is I feel like I can't interpret docs without having other docs open.*

but, xor a b => this works

Except Nat doesn't conform to the Bits interface. So I'm stuck. 📎2


that is letters rather than punctuation, it's therefore only infix if you surround it with backticks:
a `xor` b<br>

This entry was edited (Saturday, October 17, 2026, 9:44 PM)
in reply to mcc

Update: Looking at the Bits documentation, apparently integers conform to the Bits interface but natural numbers do not. This is *very* awkward. I'd need to convert naturals to integers, do the bit operation, then convert back. But it's pretty important to me that Nat `xor` Nat is closed over the naturals. Bit operations with a sign bit get really weird and performing a bit op can flip the sign bit. Honestly if anything I'd have expected Bits to be defined for the naturals but NOT the integers.
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

I am *spectacularly* confused about when I'm allowed to nest expressions in this language as well as when I'm allowed to insert linebreaks and when linebreaks require indentation. i'd really, really like a BNF or other specific description of the parsing rules other than a set of examples.

(Incidentally, I can't find the "if then" construct documented in either "tutorial"— and remember, that's the only non-API documentation I've found. If/then definitely exists, but I can't find it documented.

in reply to mcc

Consistently opinionated is okay. Definitely better than MATLAB which seems to freely mix the concept of 'language' feature and 'extra cost library add-on' indiscriminately.

Somewhere I have the book "Learn you a Haskell for Great Good" where the "Good" has been lined out and replaced with "Trauma" 😆 which kept me away from functional languages ever since.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

How do I turn 🙁 Nat into Fin 64 🙁 apparently tossing off an "if < 64" isn't good enough. With arrays I could call an "inBounds" that returned Yes or No with magic predicates but I don't find anything such in Data.Fin.

BONUS WEIRDNESS: I imported Data.Fin and tried casting Bits64 to Fin 64, which I expected to fail because that's a fallable conversion, but instead I got the strangest type error on the *following* line. I need Rust try_into() somehow.

(Fin 64 is "numbers under 64")

in reply to mcc

Okay, status, end of day four (with change). My program can run the "sample" in the AOC project statement correctly. However when run on the puzzle input, it crashes (assert line 102). There are five smaller tests in the AOC statement, but to attempt them I need to add a verbose mode that lets me introspect the register state.

This is fairly satisfying (if not correctly commented) code, to me, even if each individual line required way too much blood and tears to write.

github.com/mcclure/aoc2024/blo…

prozacchiwawa reshared this.

in reply to mcc

As of now, I do not believe I could have written as much of this program as I did if I didn't have 20,000 Mastodon followers* including many members of types.pl. In an academic setting, I could have pestered a TA. But the Idris IRC is dead, and the Zulip is super responsive BUT if I'd made a Zulip thread for each problem above the majority of threads would now be mine. Maybe I couldve made one long "HELPME" thread idk

* Yes, the site says 42,000, but *way* more than half of those are spam bots.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Me, thinking: Writing clear, relevant error messages is one of the hardest things in a programming language. It's harder in languages with inference and currying. My own languages have quite bad error messages. It's very unfair to bag on Idris for bad error messages.

Also me thinking: In Idris we don't say "expected (String, Bool) but got String" we say "can't find Applicative" and I think that's beautiful

"Yeah, applicatives just stopped existing for a moment"

"Forgot to pay your Monad Bill"

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Alright, well that wasn't so hard.

*Blinks, looks around*

Wait, wasn't I supposed to be eating breakfast?

(Notes: - Notice the "expected output", separated by commas in the filename, is printed separated by newlines in the output; haha wow it's annoying when you write an algorithm as a chain of mutually recursive functions that end by tailcalling each other, and then realize you need to add one parameter)

in reply to mcc

Okay so

Sample works as expected
Additional examples in the problem statement work. Adding register display to verbose mode revealed one (1) bug and allowed confirming those end correctly.
Problem input completes without errors.

My output on the problem input, the website says, is incorrect.

The only thing left I can do is construct my own tests against the (unclear on several points) problem statement to find what misbehavior isn't captured in the samples.

This one is going to be… painful.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Only worked on this for part of the day, but I wrote a series of, in my opinion, *extremely* good functional tests— in my opinion, I write extremely good tests— systematically testing every opcode, combination of behavior, and operand code.

I found no problems. Something is wrong and I haven't found it.

The *one* thing I didn't test yet was the branch instruction, simply because I got sleepy. Oh my goodness I had *better* have something wrong with my branch implementation or I am in *trouble*.

in reply to mcc

Incidentally, something that incredibly frightens me is that the submission procedure involves a kinda weird manual step that I don't automate in my program— the program prints out a series of numbers, and the AOC guy's instructions were "turn the numbers into a comma-separated list, then remove the commas". Uh? RN my process of turning newline-separated into unseparated values is manual and what if i got it wrong? What if the problem is ME? The fallable human? This is the stressy part about AOC
in reply to mcc

@phlip

I don't get it. Do we look at the same instructions? I'm using adventofcode.com/2024/day/17 , which does not contain the word "remove". It repeats three times that multiple output values should be separated by commas, apparently to make sure that answers are not rejected due to wrong formatting.

And I do not see a need for *manually* formatting the answer. It should not be too difficult to do it programmatically.

Or am I missing something?

BTW: A very interesting thread!

in reply to Jordan

@jrose he never suggested using newlines; he simply said "output the number"

i think the commas are so that he can give samples with non-confusing results, and i think the comma removal is so that his answer checker can be as simple as possible. but it worries me, because unnecessary detail like that makes me afraid he's Up To Something, or there's a nuance my brain is just missing, or it hints at something awful in Part 2.

in reply to mcc

aoc2024 day 17 spoilers?/speculation

Sensitive content

This entry was edited (Monday, October 19, 2026, 4:36 AM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

THE PROBLEM WAS ME. The problem was the commas. I *wasn't* supposed to remove the commas, I was supposed to include them. The problem statement isn't even oblique like AOCs even are, he just worded the sentence in a slightly odd way and I confused myself. The version of my code that passed on the AOC author's full testcase set passes on my input. I didn't even spot this myself, someone pointed it out in my mentions.

But I regret nothing. Because writing exhaustive test cases is SIMPLY WORTH IT.

in reply to mcc

AOC 2024 day 11 speculative spoilers

Sensitive content

in reply to mcc

UPDATE: Hahaha, oh heck

Okay, so without explaining "Part 2", what I now need to do is alter my part 1 program so it runs in a loop, and the output is appended to an in-memory structure instead of sent to STDOUT. The most sensible way to do this would be a Perl test harness repeatedly invoking the exe and parsing the output.

I! Don't! Want! To be! Sensible! The point was not to write software but learn something. I think I now have an excuse to finally learn something concrete about "monads".

in reply to mcc

My program:

github.com/mcclure/aoc2024/blo…

Runs a simulation over time in the IO monad, calling "putStr" and "die" as appropriate. If I were in an imperative language, I'd just change those to append to an array and throw an exception.

But monads are "programmable semicolons", right? So I should be able to have one program parameterized over a monad, a "submit value" function, and a "early terminate" function. I should be able to emulate array.push_back() and throw. The monad just handles it.

in reply to mcc

I mean, also I could just rewrite the program without a monad at all. I could do normal recursive techniques, accumulate my values in an accumulator, and terminate early with Either. But I already know how to do that, so it's not interesting. What's interesting is doing something I couldn't do, or couldn't do easily, without Haskell/Idris.

So I guess my question for Idris users is:

Do I "write my own monad"? Or is "IO" adequate for "emulate mutable state in the form of one accumulator list"?

in reply to mcc

The most educational approach is probably to do it all three ways:
1. normal recursive techniques
2. IO monad imperative program
3. Roll your own monad encapsulating the boilerplate from (1) that hopefully shows that the structure from (2) is not tied to IO, but to accumulating some state in the background and having some kind of unwind opration.

Folks will tell you to use monad transformers or effect frameworks. But I don't think that's nearly as educational as doing (1) and (3).

This entry was edited (Monday, October 19, 2026, 4:33 PM)
in reply to lambdageek

@lambdageek It is good thinking! One thing of note is that I need some kind of pause/resume feature ANYWAY, so that if one of my runs takes "too long" mastodon.social/@mcc/117468548… I can come back to it later.

One option would be to write the "normal recursive"/OCaml version first because I'm certain i can finish it within my time limit, and I can return latre and do the more-complex version without time pressure and AFTER reading, like, a book or three about this.


(Also, if you're wondering: The reason to not just accumulate in a list and then print it at the end is that some of the inputs to this program will result in *infinite runtime*, and in that case the best case is to write the updates to STDOUT as I go so I can introspect what is happening in the debug mode.)

in reply to mcc

Good news: coroutines are also a monad.
Bad news: I'm not sure there's a good way to arrive at the coroutines monad in a natural way from how you'd write the "normally", unless you just write all your code in continuation-passing style by default.

Also in this case doing the "IO monad imperative program" version is probably going to be a dead end because I think refactoring it out into a pause/resume version is not going to be very natural.

in reply to mcc

Spoiler (part 2 of the puzzle)

Sensitive content

in reply to Heribert Schütz

Spoiler (part 2 of the puzzle)

Sensitive content

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Right up until the last minute this language is giving me a cornucopia of "this thing I did before has stopped working suddenly and the error message doesn't hint why"

Here, a very simple "case" statement fails, because… because the variable I assigned to wasn't used. I was sincerely not sure if I was confused about the (seemingly undocumented) whitespace rules again. No, I just needed to use the result. But I wanted to write the expression before I tried to use it. Silly me!

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Alright. Any Idris users awake?

I want to compare two lists. That's easy to implement recursively, and I THINK it's implementable with zipWith tho docs remain… vague ( idris2docs.sinyax.net/data/bas… what does zip do if the lists are of unequal length?)

…but! It *sounds* like something the standard library would have. And indeed I find a Interface-satisfying function exists in in Data.List.Equalities…

idris2docs.sinyax.net/data/con…

…but I can't import that.

I type this post, and the explanation jumps out.

in reply to mcc

…it's in contrib. List equality isn't in the "prelude" (default) or "base" (despite the name, not default; you have to specifically import base).

The doc doesn't *say* it's in contrib. But the *url slug* says it's in contrib. I only notice this when pasting the url into this compose box.

…Also, while writing this thread, I got Idris2 maintainers begging me not to use anything in contrib because that's all stuff that's GOING to be spun out into its own library but hasn't been yet. So, uh…

in reply to mcc

Oh right, I was going to ask a question. Any Idris users awake? Two part question.

1. idris2docs.sinyax.net/data/con… Do I understand write that if I can import the package containing this symbol, a == b and a /= b on `List int` will magically work?

2. Is it surprising that I changed my ipkg to say "depends = base, contrib" and despite this, "import Data.List.Equalities" fails in the Idris executable, and succeeds in the LSP? And also list1==list2 still fails with the mystery (?a->?f?a->?b error?

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Okay. Whatever. Whatever!! At this point I go on tilt. I can't decode this documentation, I can't figure out why `idris2 -o` ignores my ipkg and `pack exec` fails without printing error messages. I know SML/NJ! I write my own list-equality helper. It takes seconds.

…oh wait, it's not letting me use the Eq interface. Odd. Fine, I'll compare ints.

…oh, there's… no such thing as… equality on ints. fine. Fine! I wanted Bits64s anyway. I—

OH COME ON HOW IS THAT NOT A COVERING FUNCTION??

in reply to mcc

At about this point a very nice types.pl user replies to point out that the reason my original == code, with Data.List.Equalities, did not work was because I mixed up |> and <|. Again.

…I…

I'm frustrated. At this point. I'm not concentrating well. I'm trying not to mention "COVID-19 post-viral syndrome" in this thread, or how much Benadryl I'm on.

Okay. Okay. It works now. As long as I run "pack exec". Which means I am now banned from getting error messages in the command line. Okay. Fine.

This entry was edited (Tuesday, October 20, 2026, 3:20 AM)
in reply to mcc

Please excuse me for my unprofessional outburst. With regard to whether my "listEq" implementation was a covering function. Although I'm still right.

EDIT: Im wrong. I was given a counterexample. I think what I should have matched in cases two and three was (_, []) and ([], _); since the case ([], []) was already excluded, those patterns can only match "lists of 1 or more items" in the _ positions, and it will work. I did not test it.

This entry was edited (Tuesday, October 20, 2026, 4:10 AM)
in reply to mcc

Also this… this is correct. This is absolutely correct. The problem was my |> / <| mixup, not which modules I had imported, and I don't have any need whatsoever for contrib, so I'm out of `pack` jail now. Okay. Alright. That's good. Okay. types.pl/@ionchy/1174710916268…

[QRT inset not provided because of the Mastodon 5 GUI reset dropping tomorrow. I've switched to masto-fe and can no longer quote boost.]

in reply to mcc

AOC 2024 day 11 spoilers

Sensitive content

in reply to mcc

AOC 2024 day 11 spoilers

Sensitive content

in reply to mcc

AOC 2024 day 11 spoilers

Sensitive content

in reply to mcc

AOC 2024 day 11 spoilers

Sensitive content

in reply to mcc

AOC 2024 day 11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers?

Sensitive content

in reply to mcc

AOC2024day11 spoilers?

Sensitive content

in reply to mcc

AOC2024day11 spoilers?

Sensitive content

in reply to mcc

AOC2024day11 spoilers?

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

TVTropes calls this the Password Slot Machine

tvtropes.org/pmwiki/pmwiki.php…

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

AOC2024day11 spoilers

Sensitive content

in reply to mcc

Okay. I have the architecture for the search program that will find my "part 2" solution clearly in mind, I am certain it will work, I have the "type-driven development" scaffold of it written down in a file, and this is just me commemorating that I *could have* finished this in the next ~2 hours before I hit the one week anniversary of this thread but I decided it was more important to lay down and sleep.
in reply to mcc

Alright. Idris question. Do you just have like… a for loop. Hiding in this language somewhere. Yes I know how to do a loop with recursion. But you've already *got* monads/"do" and sometimes it's just true that the most semantically efficient way to communicate something is "for i in 1 to 8" or whatever. You seem to have range() . I think so anyway. I've thought I found things in the stdlib before and been wrong. idris2docs.sinyax.net/data/pap…

You didn't document "if" so maye you didn't document "for"

in reply to mcc

there's a for and for_ function in the prelude. the difference is that for_ doesn't care about the output from traversing the data structure (returns m () for a monad m) but for does (like map with side effects). probably for_ is what you want. idris2docs.sinyax.net/data/pre…

also you can do range comprehensions [ 1 .. 8 ] to get a range list: idris2.readthedocs.io/en/lates…

so it should be something like,

for_ [ 1 .. 8 ] $ \i => do
... something with i ...

This entry was edited (Wednesday, October 21, 2026, 12:58 AM)

mcc reshared this.

in reply to Zoe : Void -> a

@typeswitch
So if take the Applicative to be IO:
> traverse print [1,2,3] -- traversing for a list
1
2
3
(returns: [(),(),()])
> traverse_ print (Just 1) -- traversing over Maybe
1
(returns: Just ())
> traverse_ print Nothing -- traversing over Maybe
(returns: Nothing)

One use case of the Maybe instance would be something like:
do result <- thingThatCanFail
for_ log result -- log the result if we got one
pure result

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Currently drowning in a never-ending chain of writing basic "case" or "if" statements and getting unintelligible errors like "expected =>" on a => or "expected end of expression". Trying to not run to Mastodon for help on every one. Did encounter one thing that seems so actionable I'm considering filing it:

Why are members of the sequence "0..7" not Fin 8?

in reply to mcc

*deep breath* Okay, I'm…

I'm going to finish this. I'm going to do it.

When I set this down due to the PHP fire drill, I knew *exactly* what I needed to do, and how to get Idris to do it; but I could not get the Idris syntax to cooperate— due, I *believe*, to type errors the compiler was mis-flagging as syntax errors. I've got two reasons to hope I can just sit down and get things working.

One: This post… types.pl/@ionchy/1174794602464… which might be the thread if I pull it, things start working…

in reply to mcc

Two: Holes. Perhaps holes will save me.

When I used to write a lot of OCaml, I got into this habit of writing things in a particular order, like chiseling a statue in reverse. I'd write things "in to out", smallest and most basic things first, larger scope last. This is because OCaml's extreme type inference lead to "spooky action at a distance", so if I wrote the small things last, a minor error in a small thing could cause a type error in a big thing (e.g., in entirely the wrong place).

in reply to mcc

Idris is worse about this, also it's *the type system rather than the syntax* which determine which symbols and which are types, and the error messages suck, and the LSP won't infer types if there's an error. And I didn't write my code in "check after each step" order. I just wrote it, then compiled. And suddenly found myself… it was kind of like trying to stomp out an air bubble on a carpet? Doing the reverse of my chiseling. Commenting more and more out until ANYTHING compiled. And failing
This entry was edited (Saturday, October 24, 2026, 3:27 PM)
in reply to mcc

Anyway, Idris/Haskell (or just GHC?) have this "holes" idea, where you can drop a "placeholder" value, prepend stuff with question marks, and Idris will just Not Make Assumptions about that bit. You can write your code out-to-in, while still getting the "chiseling" effect. In theory. Maybe I could learn that.

Problem: Yesterday my laptop rebooted (desktop linux seems to crash more in 2026 than it did in 2006) and now the Idris LSP won't wake up. Sublime Text LSPs do that sometimes. Aaaaargh!

This entry was edited (Saturday, October 24, 2026, 3:26 PM)
in reply to mcc

Oh. I … hm. I tried, in a terminal, launching idris2-lsp. And then I killed it with CTRL-C. And suddenly Sublime started behaving.

????

(It is possible, a little unlikely but possible, I am the first person to ever successfully use the Idris LSP with Sublime Text. I had to write my own language configuration for the Sublime LSP plugin. I didn't know how to do that before this project.)

This entry was edited (Saturday, October 24, 2026, 3:41 PM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Okay, is frickin'…

Is Sublime Text the problem? Has Sublime Text been the problem this whole time?

(Images 1,2) I understand this error. I *understand it*. What I don't understand is what it's telling me I need to do to fix it. A value X is a fin16 and it's being used at a site Y expecting a nat, or vice versa. What I expect to see is X and Y underlined. Instead I get only X, which as far as I know is *untyped at the underlined point*. I *assume* the .. coerces it into a nat.

(post 1 of 3)

This entry was edited (Saturday, October 24, 2026, 6:13 PM)

prozacchiwawa reshared this.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Oh, and I can *only* mouseover the "0". If I want to lookup the type of "shiftL" or "digit_idx", I can't.

If I run in the command line, it gets weirder. I get a nice ascii art underline which seems to be trying to underline the site of the error, but (1) it's a *different* site than the LSP underlines, and (2) actually, it's not underlining anything at all. the underline spans 3 symbols.

I want *both* underlines, and ideally, I'd get the same underlines in every tool I used.

(post 2 of 3)

in reply to mcc

So, Idris users, here's my question for you:

* Is this what you see in your editor / IDE? *

Am I seeing some kind of *error* in the LSP when it talks to Sublime, or an error in Sublime's LSP bridge? Someone earlier mentioned *their* IDE, in Idris, gives you a list of holes. If I have that I haven't found how to activate it. Would a more Idrisy IDE mean I could get positions of all four of "Integer, Integer, Fin 16, Nat"? and not just "well, eventually this "0" unifies with something bad" (3/3)

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

In the absence of an answer to the above, I return to "holes", and the hope that "holes" offer. The first thing I try: I turn the usage site for `digits` (the thing containing the bad "0") into a ?hole, so I can mouse over "digits" and see what type it is if nothing unifies with it. This is how I'd have debugged this with Merlin if I got an unhelpful error in OCaml.

…

Nope!!! For some reason, in this *one* case, mousing over digits gives me what I think is *the type of the entire do block??*

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

I agree, but literally the entire point of this entire project was to see if I could find something better than Rust 🙁

infosec.exchange/@cyberquixote…

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

With the refining tool of "let () =", and writing some *incredibly* ugly code (if I trusted this syntax enough to split things across linebreaks, writing this language would be easier), I nail the problem down.

The problem is "this function requires a number that is proven to be under 64. instead, you gave it a number that is proven to be under 21".

…

I understand why the type system differentiates them.

But why is there not a *cast*???

Numbers under 21: MAY OR MAY NOT be under 64??

in reply to mcc

Notes:

- Previous comment really is just me voicing frustration; I know how to work around this, which is to construct a Fin 64 the first time around. It will be less elegant code, but I'll manage. I *am* very frustrated, though.

- What I'm actually doing for the record is converting a number of octets to a number of bits. What I'd ideally want is a function that can multiply a Fin 21 by 3 and get a Fin 63. This doesn't… *seem* to exist. In the obvious place. Hm. idris2docs.sinyax.net/data/bas…

in reply to mcc

I feel like if I knew Rocq, I could write a proof on the underlying representation that a function that multiplies a Fin 21 by 3 produces a Fin 64. People say Idris is like writing in a language with an inbuilt proof solver, so presumably, if I took ANOTHER week, I could write a single Idris function that multiplies a Fin 21 by 3 and returns a Fin 64 and contains the various type statements that constitute the proof that should be allowed. That would probably be more fun than what I'm doing now.
in reply to mcc

Okay. Jeepers. Jeepers!!! No errors. I think by now I can sincerely say the single design decision about Idris that caused the most difficulty over this project is the decision to use Fin for the bit-shift argument to the bitwise left-shift library function.

Hey Idris folks. Say I have two lists (A,B) and I want to generate all tuples (a,b) that can be created out of one member of A and one member of B. Is there a library function for that? I can write that but it sounds library-function-y.

in reply to mcc

ok, so, I can't test right now but I believe the magic incantation is:

(,) <$> xs <*> ys

where xs and ys are the two lists.

The way this works is (,) is a binary function that turns two values into a pair of values ... \ a b => (a,b)

(,) <$> xs maps (,) over xs, in fact you could write map (,) xs instead, since <$> is another way to write map. This gives you a list [ (,) x1 , (,) x2 , ... , (,) xn ]

then <*> ys takes this list of functions and applies each y in ys to each function.

prozacchiwawa reshared this.

in reply to dyssociative function

i'm going to be honest you said that and i spent 20 minutes looking at idris2.readthedocs.io/en/lates… and trying to understand what on *earth* you could have possibly meant. to me "do" is a mysterious magic thing that has special cased behavior for <- and newline. So "do and two lists" could mean do a;b; it could mean… i don't know, a lot of things. do is not a higher-order function of three arguments, such like I could have used the type to derive what order I write things in.
This entry was edited (Saturday, October 24, 2026, 7:44 PM)
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Oh my god. The Idris users replied by giving me this wacky Do construction and unless this is just implementing `zip` it appears to work. Apparently the thing that turns this into a combinatorics engine instead of side effects is assigning it to a list, which puts you in the List Monad. This is Perl. This is literally Perl and the magic "List Context". Moreover, *this is the specific feature of Perl that blew up in my face and made writing the Perl script upthread take 8x as long as it should*
in reply to mcc

Wait how many of my "I don't understand why the syntax is blowing up on me" incidents of writing this program have this been. Like how often have I thought I was using a "do" block with return value `-> IO (List a)` but it actually had somehow derived it was return value `-> List a` so it was magically interpreting the "do" as the List monad instead of the IO monad and then something freakish happened and produced a type error I couldn't understand.
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Tolerable, but odd: Although I'm pretty sure I've successfully used the | operator for bitwise OR in actual Idris code, in the *REPL* I can only access bitwise OR by writing it as (.|.)

No other sequence of characters works. Not `|`, not `.|.`

ME: Hey I wanna do bitwise arithmetic

IDRIS2: Okay, first draw me a picture of a butt.

ME: …

IDRIS2: Come on man, do it

in reply to mcc

An important thing I should probably note at this point: I perceive that I blew through the "my first Haskell program" puzzle with relative ease and then got bogged down something awful in the "my first Idris program" puzzle, and you'd probably get that same sense reading these threads. *But* it's possible that rather than this reflecting on Idris, it's only downstream from me picking puzzle 7 for Haskell and puzzle 17 for Idris and 17 being ~6 times as hard as 7. mastodon.functional.computer/@…
in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Remember my feral list equality function that turned out to be unnecessary? Well it's back, and it compiles now, and is actually useful. This would probably look more satisfying as code if the first three clauses returned "=> True => False => False" but I actually do need the asserts.

I think…if I write a function that converts a list of octal digits into a number possessing those octal digits…the program will just work. I think it will work on the first try. Unless I forgot a "reverse". Or two

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

…wait a minute. Isn't what I want just foldl with `λ x y = (x << 3) | y`?

export octal_fold: Bits64 -> Bits64 -> Bits64
octal_fold a b = (.|.) (shiftL a 3) b

So I just plug that in and…

… what?

(This one went away if I cast [1,2,3,4] to List Bits64 but I can still be annoyed about it. By the way, OCaml likes foldl and Haskell likes foldr, right? Which one does Idris2 prefer?)

in reply to mcc

This last bit of debugging would be going so much easier if I could just figure out why there is a documented module named "Libraries.Utils.Octal" which doesn't actually exist in the standard library. mastodon.social/@mcc/117471914…

Maybe I should give up and write my own int-to-octal-string function.


There's something in the "sinyax" docs titled "Libraries.Utils.Octal". I don't find this in `pack query`, and it isn't in prelude. What is this, and how do I obtain it? It would speed up the thing I think I have to do next.

idris2docs.sinyax.net/data/idr…


This entry was edited (Sunday, October 25, 2026, 6:32 PM)
in reply to mcc

So functional programming likes linked lists, and the standard way to build a list in ML derivatives (which includes Idris) is not a ".append" like in C, JS, Rust but newelement::list, i.e., a prepend operation. This means functional programming involves a lot of generating a list then reversing it.

Anyway, what I've figured out is my automated solution search, now that it's finished, *actually* finds solutions which print *the target output, but backward*.

Sigh.

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

Okay. Yes. Straightfoward. I intentionally left my output reversed because I needed to compare it to the target string rightmost-value-first, but then I forgot to reverse the target string. Pretty quick to find.

This project is officially a

FAILURE

Because it took 12 days instead of the planned 7. If I'd finished it yesterday I'd have complained "that's 7 days, it's just dealing with PHP and '4' left me unable to work on it tuesday through friday" but it still took me two days once I resumed.

in reply to mcc

There turned out to be exactly 16 different integers that were correct solutions to my problem, and then one I found by hand was not the lowest. It appears I made a mistake on digit 3.

I am now at 11/25 puzzles completed, 9/11 completed in the time limit. I think I am going to put this project down for a while, this one puzzle was brutal. Especially the second half.

Pity, because my next two languages were Zig and MIR ( github.com/rust-lang/rustc_pub… ) and I was legit really excited about those.

This entry was edited (Sunday, October 25, 2026, 11:52 PM)
in reply to mcc

Here's my solution code for "part 2", but of course it's confusing unless you've read the "spoilers" blocks above and know what part 2 is even meant to be doing.

github.com/mcclure/aoc2024/blo…

You may find line 276 interesting.

in reply to mcc

It is my hope this is not the last time I use Idris. I feel I'm closer to Actually Getting the functor/applicative/monad distinction than ever before, and Idris is a good place to explore it, better than Haskell. However, as it is I think I'm only writing small "learning FP" programs in this language, as writing moment-to-moment practical code is just too metal-on-metal grinding painful.
This entry was edited (Monday, October 26, 2026, 12:05 AM)
in reply to mcc

The design of Idris is smart. The package ecosystem is good. This could be a good, useful language. But the base documentation and the error messages are just too lacking. The former is fixable (especially if the devs/community leaned less heavily on "make it work like Haskell, then assume everyone already knows Haskell") but the latter is more of an open question. In general, making a language with good compiler diagnostics is a harder problem than the rest of "making a language" combined.
This entry was edited (Monday, October 26, 2026, 12:04 AM)
in reply to mcc

Hrmm... I had good experience with trying erlang first because it made the things often considered quirks of Elixir (and I'm going to imagine Gleam) make sense. But I can also see how trying elixir first would let you just appreciate it (or not) for what it is.
But you should definitely consider doing them somewhat together - the BEAM family as it were

@noodlenog

in reply to mcc

Oh no...

The single worst feature of Perl IMO is the operators that do entirely different things in scalar and list contexts.

i think it messes with people's memory for what operators exist and which do what.

I strongly suspect this is one reason, for example, that (years ago) one of my team who knew Perl quite well forgot that it had a string length function and wrote his own.

(I used to be a big Perl nut)

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

i don't use idris in lsp mode, i use the idris2 mode in emacs instead.

i admittedly prefer not having things interrupt when editing and then having a list of errors when i call for it (M-x compile).

The idris mode looks like this normally for me.

if you make an ipkg file right away, C-c C-l will show the holes in the current file. I never let an idris file with errors persist because admittedly the error messages aren't easy to understand and i find them more difficult to reason about than other languages.

holes though, you can always put one in and then reason about the difference in type.

in reply to mcc

AOC2024day11 spoilers

Sensitive content

This entry was edited (Tuesday, October 20, 2026, 12:05 PM)
in reply to ROTOPE~1

Hah, I dropped into the thread with @rotopenguin's post, expecting some light-hearted programming-language humor, not some "Epic trials of MCC" thread with 1.414×10⁴ posts 😆

You have a great deal more fortitude for this adventure than I would ever have, but it sounds like you're having fun and learning stuff which is the important bit 😁

in reply to mcc

advice / what's going on -- please ignore if unwanted

Sensitive content

This entry was edited (Tuesday, October 20, 2026, 3:38 AM)
in reply to mcc

Disregarding my previous promise to know what I am talking about:
For your code that starts with

listEq : List (Eq a) -> List (Eq a) -> Bool

I think the interface restriction needs to be written like this:

listEq : Eq a => List a -> List a -> Bool

For your specialized integer code, I think you need to capitalize your int as Int or maybe Integer (so List int should be List Int)

Both these suggestions based on what I skimmed at idris2.readthedocs.io/en/lates…

As for the covering, I don't know.

I really like following you Idris 2 adventure, I wish to learn it myself some day.

I remember my intense struggles and frustration when learning Haskell a long while ago.

in reply to mcc

Based on what I can see of your program, I think the issue is with `|>`, since that's reverse function application: that is to say, `5 |> show` is effectively sugar for `show 5`. That means you're trying to take the result of `output == cpu.prog`, which is `Bool`, and apply it as a function to the value `pure`, as though you wrote `(output == cpu.prog) pure`.

Again, I can only see what's not obscured, but with those assumptions, I think you might just want `pure (output == cpu.prog)`?

This entry was edited (Tuesday, October 20, 2026, 3:21 AM)
in reply to mcc

> rewrite the program without a monad at all. I could do normal recursive techniques, accumulate my values in an accumulator, and terminate early with Either.
youtu.be/3Dc_cnj1PEc?t=12
in reply to mcc

if you can envision two monads that can both be described by a common set of operations, and you want to abstract over them, what you may want is a new interface (typeclass) that has Monad as a prereq and just exposes your operations. You could then implement those operations for the monads you're interested in, say one to update State and one to do IO.
in reply to mcc

both are sensible. In the first case you would parameterise over a monad that has two actions. this is the kind of things you can do in haskell with monad transformers. If you want to use IO you can have an IORef holding your state and mutating that IORef as necessary and do everything in IO.

Both of those are nice experiments in their own right I would encourage you to do them.

If you want to do something that's idris-specifc, here is an idea: Monads can be more powerful in idris because they can constrain what actions you're allowed to take at any point. For example you could write a monad that does not allow you to sequence further actions once you've existed the program, I wrote a gist about it juts now gist.github.com/andrevidela/3b…

in reply to mcc

By the way if you need to add one parameter post-hoc you can add a parameters block around the functions that need it idris2.readthedocs.io/en/lates…

Note that those argument can’t be modified when calling other functions in the same parameters block, so it’s not necessarily what you need. it’s the mathematical definition of “parameter”

in reply to mcc

the curly braces are used to introduce and manipulate implicit arguments, argument that you dont write down at call-site and let the compiler insert for you. Usually you can omit them and the compiler knows what you mean. For example

length : Vect n a -> Nat<br>

This is secretly
length : {n : Nat} -> Vect n a -> Nat<br>

This means that every call to the function length automatically takes an extra argument that is inferred and inserted by the compiler.

In fact, that’s how polymorphism/generics work too:

map : (a -> b) -> List a -> List b<br>

This is syntax sugar for
map : {0 a : Type} -> {0 a : Type} -> (a -> b) -> List a -> List b<br>

The 0 here indicates that the value does not appear at runtime, we want to erase types away most of the time
This entry was edited (Sunday, October 18, 2026, 7:06 PM)
in reply to Erin, the OSHA denialist

@ekatwired possibly, how do you feel about haskell?

it's a neat language in a lot of ways and i'm not sure i've encountered any objections that don't come down to either "this documentation needs some work" or "these error messages need some work". similar to perl, it appears to be a fantastic language as long as you already know it

in reply to mcc

heck this post took a turn right at the end that somehow turned my mental model of your voice directly into the voice of Grace Jones (because “roll up to the compiler” evoked youtube.com/watch?v=Tc1IphRx1p… for me) and that fucking ruled
in reply to scrottie (he/him/them)

@scrottie nice! i wrote a "runtime" version of type-checking for oo perl that we used at one of my old jobs. basically the goal was to get a backtrace at the place you passed undef or a weird type, instead of the incomprehensible place it might crash later.

it mean that every single method we wrote had some "type-annotation" boilerplate and ended up feeling like "java-in-perl" but it worked surprisingly well. @mcc @program

This entry was edited (Friday, October 16, 2026, 10:49 PM)
in reply to mcc

map_right is just map. Either is a Functor (every Monad is a Functor), so it supports map: idris-lang.org/Idris2/prelude/…. you can also discover this at the repl with :search

Main> :search (a -> b) -> Either err a -> Either err b
Prelude.Types.map : (a -> b) -> Either e a -> Either e b
Main> map (+1) (the (Either String Int) (Right 2))
Right 3

but :search produces no results for the analogous type for mapping over Left so I think it might not exist. You can just implement it yourself though.

This entry was edited (Friday, October 16, 2026, 11:10 PM)
in reply to rntz

mapLeft implementation if you don't want to do it yourself

Sensitive content

This entry was edited (Friday, October 16, 2026, 11:36 PM)
in reply to _Έλλεν Εμίλια Ά. Arson Τζαϊλου

@fogti
may or may not be useful, but what was in my brain was something like this. bound is a fin of the correct size for the input vect in doWithV5, but the vect must be at least size 5. Since index uses fin, it makes it possible to pass on the vect bound, have it be a certain size without knowing the specific size inside doWithV5.

module Main

import Data.Nat
import Data.Fin
import Data.Vect

doWithV5 : {n : Nat} -> {default 5 x : Nat} -> (prf : LTE (S x) n) -> {default (natToFinLT {n=n} x) bound: Fin n} -> Vect n t -> Maybe t
doWithV5 _ _ = Nothing

main : IO ()
main = do
let
p1 : LTE 6 7
p1 = lteReflectsLTE 6 7 Refl
let _ = doWithV5 p1 [1,2,3,4,5,6,7]
-- cant' prove
-- let _ = doWithV5 ?p2 [1,2,3]
putStrLn "success"

in reply to _Έλλεν Εμίλια Ά. Arson Τζαϊλου

@fogti
sorry didn't explain well so re-replying

the point of the fin conversion is basically as a stand in for "does my x fit in the vect i was given". thinking on it, there's no reason you couldn't just prove LT directly, but when i was writing it i was thinking: the function should be exposed to a Fin bound that is at least the size we want but ultimately up to the size of the vect.

likely more complicated than it needs to be though i suppose.

in reply to cliffle

@cliffle
It seems like it'd be a problem if you ever wanted the tail of a List1 in the usual way.

Huh. Is a:::b just not defined for b as an empty list? Is that how it works?

[edit] No wait, that should be fine. That'd be a List1 with one element. But then I'm confused. OK, I think I get it. In a:::b, b is any List, but List1 doesn't include [] as an alternative. There has to be an a.

This entry was edited (Friday, October 16, 2026, 6:18 PM)
in reply to mcc

you are really suffering here due to not understanding monads I think. (But the error messages and action at a distance are not helping.)

You want: let x = lines spec
Not: x <- lines spec

I think. But I’m guessing - that “let x = lines spec” is Haskell syntax, dunno if it’s valid Idris, currently on phone.

in reply to rntz

brief monad tutorial: with monads you must distinguish IO String from String. weird error? maybe you mixed them up.

do let x = foo; ...

is just a let-binding, so if foo: String, then x: String. if foo: IO String, then x: IO String - probably not desirable. instead:

do x <- foo; ...

now if foo: IO String, then x: String; it *runs* the computation. foo must be an IO-thing (or some other monad instead of IO, but each do-block is inside exactly one monad), otherwise this will type error.

in reply to rntz

having to maintain this distinction everywhere can result in a lot of code noise. (pure: a -> IO a) is an example: it's used when you need to just shove something in a monad. so (do x <- pure y; ...) is exactly the same as (do let x = y; ...). Often pure is used if you have two branches, one of which needs to be in a monad to do some effect, but the other does not.

I can infodump further about monads but won't unless you ask.

in reply to mcc

depending on how you feel more comfortable with you can write

Right spec <- readFile arg<br>  | Left err => die (show err)<br>let specLines = lines spec<br>putStrLn spec<br>

And this will handle the error when the file isn't read properly.

The compiler's error message contains all the information you need to figure out what's wrong, although in a cryptic way. it says "I expected an IO, but you gave me a list". if you run :t lines you will see that it does not return an IO but it returns a List. You can only use x <- f when f return the same monad as all the other expressions in the do block. And because you started the do block by using IO you can't switch it to using List at this point, although it would be valid in a different context (and that's why the message is a bit cryptic because we can't be sure what if you meant to use List and used IO by accident, or the other way around)

This entry was edited (Friday, October 16, 2026, 12:13 AM)
in reply to Andre Videla

I failed in my self-imposed goal to explain it without using the word Monad so to atone for my sin I will give a simple explanation:

A monad is a "container type", like List or IO that you can "flatten":

  • flatten : List (List a) -> List a means List is a monad
  • join : IO (IO a) -> IO a means IO is a monad.

Any f with a function f (f a) -> f a is a monad (modulo details etc etc).

This is usually not exposed or visible in other programming languages because they don't have a way to give a type to f. But in Idris you can go in the repl and ask "what's the type of List" or "what's the type of IO" and it's going to tell you:

:t List<br>Type -> Type<br>:t IO<br>Type -> Type<br>

that is, any "container type" takes a type in argument and returns another type. And so every monad is a Type -> Type
This entry was edited (Friday, October 16, 2026, 12:40 AM)
in reply to mcc

let and <- are two different things !
<- acts as both let and sorta-unwrap.

do blocs are always about a specific monad instance – here IO – and you can only unwrap that same instance inside. Simplified: if you call something that returns IO a, you should use <-. If you call something else, use let.

Here you called lines which returns a list. A list turns out is a valid monad instance (it does cool non-determinism stuff). So haskell is confused because it thinks you want to unwrap a List, which is possible in a do block on List, but you're in a do block on IO.

Anyways, yeah the error messages suck ass. As someone that recently learned haskell I agree that they don't tell you much.
I can only recommend once more that you read "learn you a Haskell for great good" because you seem confused about using monads

in reply to mcc

I think you want

let spec = lines spec

instead of

spec <- lines spec

because lines returns List String, not IO (List String); the <- syntax is for when the thing on the right-hand side returns an IO.

the explanation for why that’s the error message you got contains the word “monad”; one sec, I’ll try my best in a further message

in reply to Gaelan Steele

right, so a Monad is a typeclass (what in most languages you’d call an interface), which represents some sort of “wrapper” around another type. it has an operation, called >>= or “bind”, which takes a Monad<T> and a function(T -> Monad<U>), and returns a Monad<U>. (there’s also “pure”, which just takes a T and returns a Monad<T>)

(I’m playing fast and loose with notation here - by Monad<T> I really mean Foo<T>, where Foo implements Monad. different kinds of Monad aren’t generally interchangeable)

examples of monad-shaped things you’re probably familiar with include:
- Promises from JavaScript etc. The bind operator is .then() - it takes a promise, and a function that turns its result into another promise, and gives you a promise for the second result
- Maybe/Option from Rust etc. The bind operator is what Rust calls .and_then() - it takes an Option, and (if it has a value in it) runs your function to get a new value, and returns an Option that’s None if either the original Option was None or your function returned None

in other words, it’s an abstraction for chaining a bunch of steps, each of which have some sort of side effect like “block on IO” or “maybe return null and render the remaining steps pointless”.

Idris’s IO is a monad, and indeed conceptually not far from a JavaScript promise (though, unlike a Promise, creating an IO and discarding it doesn’t immediately go do the thing)

do notation is syntactic sugar for a chain of bind calls, a bit like how JavaScript's async/await is syntactic sugar for a chain of .then() calls. "<-" is the equivalent of await. do notation works for any kind of monad.

annnnnyway, the problem is that List is also a monad (the semantics are besides the point, but roughly the idea is that you can have a series of operations on each item of the list, each of which might produce zero or more list items for the next step to process). so the compiler isn’t sure if your do block is trying to use IO or List as its monad of choice

hopefully that made a nonzero amount of sense!

This entry was edited (Friday, October 16, 2026, 12:24 AM)
in reply to mcc

btw if you have a repl handy, the :doc command might help you out. Something like :doc show or :doc Show. You can also see all the signatures of a module by using :browse like :browse Prelude.

You can also dynamically load module in the REPL (although that won't load them in the file) and inspect what they export:

:module Data.String<br>:browse Data.String<br>

or import the module in your file
import Data.String<br>

And then reload and browse the module
:r<br>:browse Data.String<br>

Small tidbits that should be advertised earlier in the tutorials
in reply to mcc

idris2docs.sinyax.net/ has docs searchable by function name, it seems.

you can import & get some docs at repl:

Main> :?
... lists all colon-commands
Main> :import System
Imported module System
Main> :doc readFile
... docs for readFile
Main> :browse System
... list of things defined in System
Main> :search Int -> Int
... searches by type, NOT by name.

warning: it appears to assume your terminal is light-on-dark? at least for me it generates some white text on my default-white background.

in reply to mcc

yes but with caveats; when people read "spend all day in the repl" it's often read as "spend all day looking at the repl prompt" but the real meaning is more like "your editor is constantly connected to the repl and usually sending entire files over to it"

(you don't actually spend that much time looking at the repl itself)

in reply to Zoe : Void -> a

this types.pl/@pigworker/1174412037…
This entry was edited (Wednesday, October 14, 2026, 8:50 PM)
in reply to mcc

there's a load of cool stuff in the FP/interesting type systems world that's quite simple, and really practically useful, but was invented by people from a mathsy background so is just phrased in a way that's alien to people who came from the programming side. I'd really like to fix this by rephrasing everything, but I know it's perilous to make new names for existing things as it can lead to confusion...
in reply to Alaric Snell-Pym

I've read @edwinb 's type driven development with Idris book and The Little Typer, now watching @pigworker 's lectures as they come out on YouTube; there's a YouTube series on homotopy type theory which started well but lost me after a point, I'll go back to it again later.
in reply to Alaric Snell-Pym

@kitten_tech One thing about my current lecture series is that it's for first years who have just started uni. So although the material is bursting with categorical structure, I am ruthlessly suppressing categorical language.

Category theorist interlopers are given a bingo card full of words. They get to cross off those words one by one, as I very carefully avoid saying them.

@mcc @edwinb

in reply to mcc

AIUI (as an idris turbonoob, and based on the Compile To Executables section here: idris2.readthedocs.io/en/lates…) it does actually compile to whatever language you're targeting. i think chez then can get compiled into Actual Native Executables? no idea if this is also the case with racket
in reply to mcc

I definitely think the awkwardness of Haskell is incompleteness, not a bug. I've tried to work on it for years, but I'm getting to be resigned to being not smart enough to make real progress at it. Specifically, I think the monad business is going at it the wrong way. You can express all that as effect types and get it completely out of the algorithmic syntax and into the type syntax, where you can use inference and type definitions to package it arbitrarily nicely.
in reply to Teemu Kalvas

But you definitely don't need monads to express evaluation order dependency. You can get the same by having lazy evaluation except that effects (which the type system describes) self-serialize. This has a constructive proof where I implement a transformation from this syntax to a Haskell-core-like completely lazy uncomplicated evaluation model. Which I probably should write up because it's the only truly usable result I have, I guess.
in reply to Vélimir

@vchakhno I dunno, vibes just felt funny. Chunky, awkward syntax and the code and documentation all uses a b c d as variable names. Also to be clear the reason I did not like it between the years 2001 and 2025 was i couldn't frickin figure it out.

I posted my diary of learning Haskell last year here: mastodon.social/@mcc/114433465…


RE: mastodon.social/users/mcc/stat…

in reply to mcc

I can't really speak for the syntax, seems at its core like lambda calculus + pattern matching + let and where + do notation. I'm familiar with those so that's OK. Not sure how close it maps to ML. Not a fan of the slight differences between case and pattern matching. Multiline sometimes doesn't do what I would like.

I wish there was a dup operator (W combinator), basicly (\f x -> f x x). Somehow every other combinator of BCKW has their own.
I like how operators have slight variations for ease of use. <=<, <$, <*, *> ...

If you're not familiar with using Functors and Applicatives I suggest taking a look at "Learn you a Haskell for great good" which is a free website that's usually recommended to learn Haskell. That's the one I recently learned from, and enjoyed the whole way. It explains them with tons of examples, it makes them really intuitive.
But maybe you've been through this already

I feel like the single letter variable names have their meaning either in their type, or in the algebraic structure they're part of. If you don't know the structure already you're fucked, good luck going from the laws to the use cases...

Personally I've been looking specifically for books and blog posts about common patterns in haskell in order to learn about those structures.
One such example are optics, I haven't seen them yet but they're on my list, and I have a rough idea what Lens/Prisms are for thanks to previous exposure.

Uh. Sorry for the text dump. I'm low on sleep. I hope it's informative somehow.

This entry was edited (Thursday, October 15, 2026, 4:17 AM)
Unknown parent

@dysfun so here is a question


Okay important question

I have a vague sense Haskell has "monads" and Idris has "applicatives". Idris in fact seems to have both— idris2.readthedocs.io/en/lates…

If I say "do" I've made a monad and if I say "[| … |]" (ugh, ocaml at its worst) that's an applicative. Difference isn't clear. If I just write monads and ignore [||] in my learning-Idris program am I Missing Out?

I still don't know what an Effect is. I thought it was the Effect Monad but the Idris manual talks like applicatives are Effects.


Unknown parent

The media in this post is not displayed to visitors. To view it, please go to the original post.

I think in principle this helps, one problem is the words "Monad", "Applicative" and "Functor" are in this screenshot black boxes. or are these *definitions*? Does => mean "I am defining the Monad/Applicative/Functor typeclass to be a thing that can do this?"
This entry was edited (Wednesday, October 14, 2026, 8:14 PM)

mcc reshared this.

in reply to mcc

@dysfun shameless self-plug for the tutorial i wrote specifically for the case where you are using monad but don't have all the theoretical background that you think you need

raphael-proust.github.io/code/…

(text in english, code in ocaml)

some people told me it was useful so maybe also useful to you. if not then i'm sorry for the noise.

Unknown parent

@dysfun all right, but I want to be clear I have *never*, literally never, run a program from the "run" option in Sublime Text and I'm actually not sure how to invoke it. I also really, *really* need to be able, on each invocation, to select a file to use as input. That's critical to my use case. That to me implies a command line executable
in reply to mcc

@dysfun

for running outside the idris environment, the model is that idris2 --build builds what's in your .ipkg file (example here github.com/prozacchiwawa/idris… ). it drops the finished exe in ./build/exec.

the main module of your program needs a "main : IO ()". unlike ocaml you can't do side effects at the top level.

Unknown parent

@dysfun @Andrev It also takes 1 minute and 53 seconds on an incremental build if I change the string "Help" to "Helx".

The way I installed idris2 was I installed Racket via apt, and then I ran a bashfile curled from the "pack" website. On the first step, it asked me my scheme interpreter, [racket] was the default [possibly because chez was not installed]. It was *very* slow.

How do I switch from "racket" to "chez"? Do I rerun the bash? Do I have to uninstall the old version first?

mcc reshared this.

in reply to mcc

@mcc @gaytabase The type signature syntax is a little weird until you understand it.

So take the example of (<$>), which as you've seen has a type signature of Functor f => (a -> b) -> f a -> f b

What the Functor f => is saying is that for the remainder of the type signature, f represents any kind of value that is an instance of the Functor typeclass, but every instance of f has to be the same kind of Functor.

In other words, IO is a Functor and a Maybe is a Functor, so (a -> b) -> IO a -> IO b would be valid; (a -> b) -> Maybe a -> Maybe b would be valid, but (a -> b) -> IO a -> Maybe b would not be valid, because IO and Maybe are different kinds of Functors.

Maybe that helps?

Unknown parent

The media in this post is not displayed to visitors. To view it, please go to the original post.

@Andrev @dysfun imagine i deleted ~/.local/state/pack, re-ran the bash script that installs pack, and selected chezscheme this time. then i delete my ./build and re-run idris2 -o. And I get this message.

What do you make of this?

in reply to mcc

The media in this post is not displayed to visitors. To view it, please go to the original post.

@dysfun pack is the way to go, you have a pack config file in your .config. it has a scheme field on which you can put the executable name for your version of scheme (assuming its installed). For me it’s “scheme” on the mac and “chezscheme” on linux, might be different for you. There should be nothing else to change, pack will use the right version of scheme onwards

edit: added screenshot of my config

This entry was edited (Wednesday, October 14, 2026, 9:37 PM)
Unknown parent

@Andrev @dysfun

1. Typing out the command does not change the outcome.

2. time pack exec src/puzzle.idr does work. However it takes 1 minute 51 seconds. so i have not solved the problem from the racket version. a 2 minute iteration time is survivable but pretty painful.

Additionally, although the bash script was told to use chezscheme, when I run "top" while pack is running, I see "racket" is using 100% CPU.

Note that i do not have an ipkg file anywhere.

in reply to mcc

@dysfun

this is the error that idris throws when the path given cannot be found. It looks like the argument parser injested the string ending in "#!/bin/sh" which is clearly clearly wrong on multiple aspects.
2 questions:

  • is if different if you use pack exec src/puzzle.idr?
  • is it different if you type out the command rather than using !?
in reply to Andre Videla

The media in this post is not displayed to visitors. To view it, please go to the original post.

@dysfun Here is another potential source of confusion. your version of idris installed by pack might not be the same as the one installed by the system. here is an example where the version in bin/idris2 is not the same as the version invoked by pack.

So if you killed pack and reinstalled it, you might not necessarily have killed the old version of idris

EDIT: This is one of the reasons doing anything via pack is a lot more reliable because it will pick the correct version of idris for you current project and keep that up to date, including libraries and tools like idris2-lsp

This entry was edited (Wednesday, October 14, 2026, 10:24 PM)
Unknown parent

@dysfun oh my god what is going on with racket? Yeah using chez scheme takes 0.36s (of which 0.3 is spinning up the chez runtime), but using racket takes 7.68s
<br>time idris2 hello.idr -o program<br>idris2 hello.idr -o program  0.36s user 0.08s system 96% cpu 0.452 total<br><br>time idris2 --cg racket hello.idr -o program<br>idris2 --cg racket hello.idr -o program  7.68s user 0.62s system 96% cpu 8.560 total<br>
Unknown parent

@Andrev @dysfun apt-cache search idris doesn't turn anything up. I'm using Debian Trixie. Everyone said pack was pretty good so I'd be happy to use pack if it can work.

In my opinion, it should be possible to move from a racket install to a chez install without the assistance of idris2 staff. IMO the bash script, when it fails noting a duplicate install, should recommend pack uninstall instead of removing one folder, and pack uninstall should kill (or offer to kill) the config file.

in reply to mcc

@dysfun couple things:

  • idris2 and pack documentation were written independently of each other so they don't explain how to properly delete both
  • here are the docs for what pack uninstall does and doesn't do github.com/stefan-hoeck/idris2… notably it won't change the existing config file
  • idris2 itself can be installed via your OS's package manager so removing it depends on how it was installed in the first place, but pack won't interfere with that by default
in reply to mcc

@dysfun @Andrev

I have had no luck getting idris2 built and running. There are chez-related test errors in channels (and this is pulling both chez-scheme and idris2 from latest git sources), and it appears to have been this way for some time (unclear how long, and I do not currently have the spoons to dig). I did not try a Racket-based situation, so I may attempt that later.

in reply to mcc

@Andrev @dysfun I filed this bug on Idris:

github.com/idris-lang/Idris2/i…

And a second bug on Pack:

github.com/stefan-hoeck/idris2…

in reply to dyssociative function

@dysfun @Andrev

Arch derivative, unfortunately. I haven't been able to push myself back to Gentoo.

idris2-git, chez-scheme-git, idris2-pack-git (all AUR because apparently nobody at arch packages it), though pack never happened because idris2 never succeeded in tests, and pack depends on it. I would attempt to debug, but I'm sick today and don't have the energy.

There's an issue somewhere in one of idris2 or chez-scheme which describes test failures in a container, and that issue perfectly describes the symptoms I see.

Unknown parent

mastodon - Link to source

mcc

@Andrev @mhcat @dysfun ok so on that note

$ pack exec src/puzzle.idr abcd
abcd

# At this moment I edit puzzle.idr so it no longer compiles

$ pack exec src/puzzle.idr abcd
[ fatal ] Error when executing system command.
Command: "/home/mcc/.local/state/pack/install/b6cbc25d5cd2ef2a250556266fd7b68dfc360f8b/idris2/bin/idris2" "--cg" "chez" "--source-dir" "src" "--cg" "chez" "-o" "_tmppack" "src/puzzle.idr"
Error code: 1

# Is this error messaging surprising?

in reply to mcc

@dysfun Good call, it's also quite likely to be fixed with pack. Idris repo is much slower. Also the maintainer of pack also wrote the better idris2 tutorial so feedback there will also be welcome github.com/idris-community/idr…
in reply to dyssociative function

@dysfun No clue, I don’t remember being such a big difference in the past. This must have happened in the last year or two. I’m sure this is something we can ask the racket people about, we’re probably passing incorrect arguments to racket (or overly conservative ones)
Unknown parent

The media in this post is not displayed to visitors. To view it, please go to the original post.

@dysfun that's not the part that scared me actually. what scared me is the implications concerning the import statement. Say I change "System.File.ReadWrite" into "Console.App.FileIO". I get error "Undefined name 'Control.App.App'"

I add "import Console.App". I get A DIFFERENT ERROR

What happened there??

Am I importing… typeclasses?? Is this like when having a trait in scope in Rust changes which kinds of inferences are possible?!

mcc reshared this.

in reply to Andre Videla

@dysfun By the way, since you mentionned you don't have an ipkg file: You will need one to use lsp, you can try:

  • idris2 --init and set the source directory in src and place your .idr files there
  • pack new bin helloWorld and that will setup a whole project for you including pack.toml, helloWorld.ipkg and test folders
in reply to mcc

@mcc @gaytabase If it hasn't been explained elsewhere, the hint is telling you that the FileError type is an instance of the Show typeclass (which defines the show function). It basically says "I want to be able to represent values of this type as a String."

The naming convention is not particularly intuitive, but it's pretty much so baked into Haskell at this point that changing it now would break just about everything. Still, it's not as bad as Lisp's car and cdr. 🙃

in reply to Andre Videla

@Andrev the only thing i remember was some comment a couple of years back (i think it was edwin?) saying he had to change the gc options to make performance better?

but like 2 minutes to compile hello world is clearly beyond the pale. even idris1 didn't take that long!

Unknown parent

yeah, type-driven development and hole programming benefit a lot from editor integration, and they're completely orthogonal to how you choose to run your program or whether it's a CLI tool.

now you can do much of this at the terminal, i believe @foxy kinda had to because the vim plugin was terrible. but like, it's definitely not getting the best out of it.


@dysfun@treehouse.systems I don't remember the plugin to be terrible though, so I am not sure whether I was using the REPL or not. I was at the very least using idris2-vim and the Idris2 LSP together for sure.

Unknown parent

mastodon - Link to source

mcc

@dysfun @ionchy I need to map over a list of strings and convert them to ints with parseInteger. If even one of them fails, I need to terminate early. I don't have collect(), so this seems to imply I need to go to the map/fold/filter bag of magical second order functions and find some entirely other version of map which has early termination.
in reply to dyssociative function

@dysfun
Here is what I know of what’s going on for chez cheme, and how that relates to other codegens:

  • The compiler being a scheme program needs to start the scheme runtime. Chez sheme takes about 300ms to bootup, so every invocation of the compiler takes at least that much
  • typechecking of such programs is essentially instantaneous
  • compilation takes a while. we generate scheme code and then we rely on chez to compile it and optimise it.

once we emit scheme code we call racket or chezscheme and have them compile and optimise the executable, this can take a while especially when linking large projects.

For a hello world this should be fast, no idea why racket is so slow. Chezscheme performs as expected (0.36s) where 0.3 is taken by booting up the runtime, and 0.06 by compiling the executable

Unknown parent

@dysfun @ionchy concretely,

Main> traverse (\x => if x > 5 then Left "too big" else Right x) [1,2,3,4,5]
Right [1, 2, 3, 4, 5]
Main> traverse (\x => if x > 5 then Left "too big" else Right x) [1,2,3,4,5,6]
Left "too big"

so (traverse f list) is basically list.map(f).collect::<Result<_>>() in Rust.

This entry was edited (Friday, October 16, 2026, 5:21 PM)
Unknown parent

The media in this post is not displayed to visitors. To view it, please go to the original post.

@dysfun right and if you use :doc you can also see that FileError has a Show, it's the last line in the screenshot.

You can do this for any type, if you use :doc it will also tell you what interfaces are in scope for that type, the main ones being Eq, Show, Ord, etc

Unknown parent

mastodon - Link to source

mcc

@dysfun

1. I see that. However, semantics are not the only important thing to me. Ergonomics are very important. As you can see from my conversation with porglezomp, not knowing which of Left and Right is "Error" vs "Ok" is messing with me bad.

2. I'm not using map anymore. I'm using "traverse", and I'm using Data.Either "mirror" to switch lefts and rights. Traverse doesn't switch anything either; however, it chose different semantics for Left and Right than I was using (hence me using mirror)

in reply to mcc

@dysfun 3. I'm getting an error when I try to traverse over a List1. Is the error appearing in the "wrong place", and in fact what's happening is the type unifier is angry I'm returning a List1 from a function that's typed as returning List?

Actually this is a problem. I *want* to return List. Zero values is an option. I guess I need to somehow convert the List1 to List

in reply to _Έλλεν Εμίλια Ά. Arson Τζαϊλου

@fogti @dysfun it is meant to turn a String containing comma-separated values into a sequence of Strings. I understand split cannot return 0 values, I assume I'm handling that special case elsewhere, but to special-case returning an empty List I must unify the List1 returned by split with the List returned by my special case.
in reply to mcc

@dysfun @ionchy

I feel like you might invite a number of l33t h4ck3r solutions that aren't necessarily succesful in explaining themselves. It might be worth going through reinventing the wheel first before jumping to the magical incantation of higher order functions that make this work.

I need to map over a list of strings and convert them to ints with parseInteger. If even one of them fails, I need to terminate early.


From this I get the feeling that you want to write a function

parse : List String -> List Int<br>

and stop or "crash" when something doesn't parse, here is something you can do:
parse : List String -> List Int<br>parse [] = [] -- we're done<br>parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => parse xs -- skip the ones that don't work<br>           Just i => i :: parse xs<br>

This is the bog standard recursive function that traverses a list, nothing fancy here, no higher order function, no magic traverse or Applicative.
And then when you're parsing the element in main you can kill the program post-hoc
main : IO ()<br>main = do<br>  args <- getArgs<br>  let parsed = parse args<br>  if length parsed /= length args<br>    then die "couldn't parse arguments"<br>    else ?rest -- continue the program<br>

This is the first most simple most declarative way to write this program that one should write before trying to interleave monadic control flow with applicatives etc.
in reply to Andre Videla

@Andrev yes, sorry, what i mean is selecting the racket codegen is still running it under chez, no? just like i can select the javascript codegen and it's still running under chez? i guess it has to call racket afterwards?

but that's clearly a lot slower. and apparently on the scale of compiling hello world entirely on racket, that's 2 minutes.

Unknown parent

@dysfun Looks like that's a no.

Error: While processing right hand side of main. While processing right hand side
of main,step. Can't find an implementation for Cast Bits64 (Type -> Nat).

src.puzzle:118:16--118:27
114 | _ =>
115 | die "Unexpected opcode"
116 |
117 | step (NewCpu ip reg prog) =
118 | let ip_idx = cast ip Nat in
^^^^^^^^^^^

Warning: compiling hole Main.main

in reply to Andre Videla

@dysfun @ionchy

Then you can start to progressively add higher order functions. for example, you mentionned map and here is how you can write the same parse function with map:

parse : List String -> List Int<br>parse ls = catMaybes (map parseinteger ls)<br>

This works because catMaybes : List (Maybe a) -> List a will do the work of skipping elements that are Nothing.
Unknown parent

What possible backend could allow Bits64 values that don't admit that Nat representation? Or are you saying that Bits64 could on some backend be signed. Because I'm using it to represent naturals and if it's possible for a non-natural to be stored in a Bit64 then my program has a correctness problem
This entry was edited (Saturday, October 17, 2026, 11:09 PM)
in reply to mcc

@dysfun by the way, Nat is not obviously a subset of Bits64 in Idris:

Nat is an inductive datatype, it's semantically a linked list of empty nodes. And it represents unary numbers starting from zero. Nat is defined as

data Nat = <br>  Z -- zero<br>  | S Nat -- successor<br>

If we didn't aggresively optimise away this representation, each nat would be a heap-allocated list of pointers. This may sound scary but it's in fact the right tool for the job, and it's compiled to BigInt.

Bits64 is an opaque type with backend-specifc semantics. For example the way they perform between the refc backend, node and chez is completely different. Typically, Nat is faster on chez than Bits64.

in reply to mcc

@dysfun @amy that looks relatively normal for the type of exercise that is AOC. I think the next big conceptual step here is to describe the CPU with a concrete record (and the opcodes as data) and the interpreter as modifying the record. This way you can split the execution of the CPU and the parsing of the instructions.
This entry was edited (Friday, October 16, 2026, 10:29 PM)
in reply to mcc

@dysfun When the code is compiled they should both be represented as a vector of 64 bits. The difference lies in the semantics of the code as it is being compiled and analysed.

When we are looking at Nat the compiler sees it as a unary algebraic data type. That's necessary to achieve features like termination checking (totality), compile-time evaluation of types like Vect (3 + 4), and propagation of invariants like Fin n -> Fin (S n). All this compile-time analysis can only be done for algebraic data types. But because Bit64, Int32, etc are not algebraic data types, they are FFI-types we can't compute with them like we can for Nat. They are totally opaque from the perspective of the typechecker.

If we could somehow turn Bits64 into an algebraic data type, then we could more closely match it to Nat. And in fact we can! Bit64 is equivalent to the algebraic data type Vect 64 Bool.

And now you can see that the semantics of Vect 64 Bool are not the same at all as Nat. the first one is a list of fixed length of booleans and the other is a possibly infinite list of empty nodes, there is no type theory in which those types are subtypes of each other.

in reply to mcc

@dysfun cast is a little bit misleading if you expect some sort of type coercion to happen. cast is a function from the Cast interface that is "known to be lossy". You can implement cast between any to types and do any sorts of shenanigans like
cast : Vect n a -> Bool<br>cast [] = True<br>cast _ = False<br>

The typechecker has no knowledge of the final bit representation of the data and that does not inform what can or cannot be cast
in reply to mcc

The "if x then y else z" is one expression; to break it up over multiple lines, later lines (the "then" and "else" lines) need to be more indented than the first line. Indenting the "then" and "else" lines should remove this error. You might be right about the "die" also being incorrect, but that will show up as a type error, which will look more like "cannot unify type x with type y".
This entry was edited (Sunday, October 18, 2026, 12:08 AM)
in reply to mcc

@dysfun I wrote a big draft and lost it and now I'm not even sure how to answer this. as a summary

  • the "number" will be unchanged
  • the data representation at runtime will not necessarily be the same
  • The cost of the cast will be O(n)
  • For type-safety reasons there is no way the compiler can treat those types as being related in any way
in reply to Andre Videla

@Andrev @dysfun Hey so

I would like to file an issue on Idris2

complaining that :doc for the following items

Data.Fin.natToFin
div
mod

do not have text descriptions

natToFin is a real problem because the argument order is NOT obvious
div i think is integer divide drop remainder but i'm not sure
mod is a real problem because you need to explain behavior with negatives

is the github main Idris2 the place to file issues concerning stdlib/docs

in reply to Andre Videla

@dysfun @ionchy

Of course your original intent was to write an imperative program with control flow and in the previous example we're delaying the control flow operation to later, and that's less efficient. What we want is a function that will first tell you to break control flow as you are going through the list. Someone mentionned Either before but we can also use Maybe and for that we should go back to our bog standard recursive implementation:

The first change is to return Maybe (List Int) to indicate that if we need to abort the program, the parse function returns Nothing:

parse : List String -> Maybe (List Int)<br>

After that we modify our implementation , I'm going to put holes for the compilcated parts
parse [] = Just [] -- <br>parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => ?h1<br>           Just i => ?h2 <br><br>

If you ask the repl :t h1 it will tell you:
   x : String<br>   xs : List String<br>   p : Maybe Integer<br>------------------------------<br>h1 : Maybe (List Int)<br>

At this point of the program we need to return either a list, or a Nothing. because this is the branch where parsing failed, we are going to return Nothing indicating that we return immediately and abandon building a list of integers.

if you ask :t h2, you see that we have an integer with i:

   x : String<br>   xs : List String<br>   i : Integer<br>   p : Maybe Integer<br>------------------------------<br>h2 : Maybe (List Int)<br>

But we also need to compute the rest of the list, we only have the head element. And this head element is useless if there is a parse error later. So we compute the rest of the arguments first:
parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => Nothing<br>           Just i => let<br>             rest = parse xs<br>             in ?h2<br>

Now rest : Maybe (List Int) is the rest of the strings parser as integers, if there was an error in the rest, this would be Nothing. If everything parsed correctly, this would be Just, we do case-analysis to explore those two branches:
parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => Nothing<br>           Just i => let<br>             rest = parse xs<br>             in case rest of<br>                     Nothing => ?h1<br>                     (Just is) => ?h2<br>

now h1 : Maybe (List Int) and it's in the branch where something went wrong with the rest of the list. in this case, we can drop the i and return immediately with Nothing
parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => Nothing<br>           Just i => let<br>             rest = parse xs<br>             in case rest of<br>                     Nothing => Nothing<br>                     (Just is) => ?h2<br>

For h1 : Maybe (List Int) we know that i is the correctly parsed "current" element and is is the rest of the correctly parsed future elements. This means everything has gone well and we can return a value with Just and cons our element and the rest of the elements together:

which leads to the following function:

parse : List String -> Maybe (List Int)<br>parse [] = Just []<br>parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => Nothing<br>           Just i => let<br>             rest = parse xs<br>             in case rest of<br>                     Nothing => Nothing<br>                     (Just is) => Just (i :: is)<br>

Again, no higher order function, no l33t h4ck3r magic, just functions, pattern-matching and recursion.

Now you can call parse and if you get Nothing you can kill the program, and if you get Just you can proceed

Sorry this was a bit long

This entry was edited (Friday, October 16, 2026, 6:50 PM)
in reply to Andre Videla

it's bed time for me but it occurs to me that I wrote a lot of similar code for AOC 2020 if you want some inspiration or are just curious. There are accompanying reports along with the code, for example day 8 had a basic cpu:

Unknown parent

AOC2024day11 spoilers

Sensitive content

in reply to Amélia Liao 🍊😈

@dysfun the error is garbage but both error messages are pointing out that neither possibility for the overloaded name split works because you've only given it one argument. the List Int on the right of the mismatch is coming from the type signature (through mirror), the function type on the left is because split is underapplied
in reply to mcc

@dysfun just like everything, there is an infinite rabbit hole depending on your affinity:

If you're dead set on high performance bit-level operations I encourage you to look at Data.Buffer. Either your will rejoice or recoil in horror.

There is yet some more type theory involving linear types for fast array manipulation and idris2-array is the state of the art in that regard github.com/stefan-hoeck/idris2…

Finally there is the way functional programmer go about those challenges and that's to parse away from the fiddly bits and into a small and well defined set of types that exactly capture the semantics of the program

Unknown parent

mastodon - Link to source

mcc

@dysfun Presumably I imagine I'd write a proof. mastodon.social/@mcc/117497422…


I feel like if I knew Rocq, I could write a proof on the underlying representation that a function that multiplies a Fin 21 by 3 produces a Fin 64. People say Idris is like writing in a language with an inbuilt proof solver, so presumably, if I took ANOTHER week, I could write a single Idris function that multiplies a Fin 21 by 3 and returns a Fin 64 and contains the various type statements that constitute the proof that should be allowed. That would probably be more fun than what I'm doing now.

Unknown parent

mastodon - Link to source

mcc

@dysfun That sounds like the most reasonable way to implement Fins, but presumably I'm doing something very silly if I use believe_me in a proof language? What I'm actually going to do is multiply by three BEFORE I convert from nat to fin and have the runtime check check against 64 instead of 21 (and the runtime check is unavoidable anyway because the number of octets is determined by input from a file)
Unknown parent

mastodon - Link to source

mcc

@dysfun based on various conversations i've had over the last week and a half, i'm feeling pretty certain that you are what a "normal idris user" looks like and i am not. i am trying to write Idris as if it were OCaml with a do construct. It's going very badly. i suspect anyone who tries to write idris this way doesn't continue writing idris very long.
in reply to Andre Videla

@dysfun @ionchy

From this you can start adding back higher order functions, for example the case-analysis on Maybe is in fact the map function for maybe:

parse : List String -> Maybe (List Int)<br>parse [] = Just []<br>parse (x :: xs) =<br>  let p = parseInteger x in<br>      case p of<br>           Nothing => Nothing<br>           Just i => let<br>             rest = parse xs<br>             in map (i ::) rest<br>

The intermediate variable names aren't necessary, you can inline everything:
parse (x :: xs) =<br>  case parseInteger x of<br>       Nothing => Nothing<br>       Just i => map (i ::) (parse xs)<br>

the case analysis on parseInteger looks like map but this won't work because the return type is also a Maybe, this is where bind (or >>=) becomes useful:
parse (x :: xs) =<br>  parseInteger x >>= \i =><br>       map (i ::) (parse xs)<br>

and it turns out that this is exactly what do-notation is for:
parse (x :: xs) = do<br>  i <- parseInteger x<br>  map (i ::) (parse xs)<br>

I don't expect anyone to follow through all those steps at the begining, but having this sequence of step is handy to help make the connection between higher-order functions and other existing patterns in the language. The more you write repetitive code, the more you might think "huh, is there a function for that?" and seeing some of them here is a good hint for things to look out for.
This entry was edited (Friday, October 16, 2026, 6:47 PM)
Unknown parent

mastodon - Link to source

mcc

@dysfun well, if "trait" means an implicit "…in Rust", i actually do often find Rust's trait magic frustrating and if Rust didn't have such good error messages I'd probably find it intolerable, But also, Rust is different because it has Turbofish.

Can I say something like

do : IO ()
x <- 3
...

And *definitely* the do block believes it's -> IO () and errors if something else is inferred? That's what I'd need to be comfortable with this

Unknown parent

mastodon - Link to source

mcc

@dysfun i agree that writing more short functions would help here. in the absence of short functions, i am just going to note it's funny to me you *did* just replicate a flaw of perl (assigning to lots of variables that are only used once, because it's possible to construct long expression chains, but if you do it's likely something will implode)
Unknown parent

mastodon - Link to source

mcc

@dysfun In terms of the formalism, yes, that's correct. In terms of the user mental model, the commonality is you write a string of characters which is OK by itself and then if its immediate context isn't what you thought then you get a bad result. The "bad result" in Perl (silent misbehavior) is worse than the "bad result" in Idris (cryptic type error), but the "bad result" in Rust or OCaml (good type error) is categorically better than those other two. Idris and Perl both present a brick wall
in reply to mcc

@dysfun Fun fact: this partially has to do with Idris' type theory as well. OCaml and rust are for the most part what is called "simple types with let-bound polymorphism", and a feature of that type theory is that you can always infer a type from its term. Idris has dependent types, which includes in a sense "true" polymorphism. This "true" polymorphism turns type inference into an undecidable problem for the general case, making type error messages in turn a lot more difficult.
Unknown parent

@dysfun there's also the secret third notation that i just remembered ... list comprehensions

[ (x,y) | x <- xs, y <- ys ]

this is the same as the above but specifically for lists.

idris2.readthedocs.io/en/lates…

This entry was edited (Saturday, October 24, 2026, 7:54 PM)

This website uses cookies. If you continue browsing this website, you agree to the usage of cookies.

⇧