Hi, I'm who's behind Fedify, Hollo, BotKit, and this website, Hackers' Pub!

Fedify, Hollo, BotKit, 그리고 보고 계신 이 사이트 Hackers' Pub을 만들고 있습니다.

FedifyHolloBotKit、そしてこのサイト、Hackers' Pubを作っています。

嗨,我是 FedifyHolloBotKit 以及這個網站 Hackers' Pub 的開發者!

Website
hongminhee.org
GitHub
@dahlia
Hollo
@hongminhee@hollo.social
DEV
@hongminhee
velog
@hongminhee
Qiita
@hongminhee
Zenn
@hongminhee
Matrix
@hongminhee:matrix.org
X
@hongminhee

BotKit 0.2.0 Released

We're pleased to announce the release of BotKit 0.2.0! For those new to our project, is a framework for creating standalone bots that can interact with Mastodon, Misskey, and other platforms without the constraints of these existing platforms.

This release marks an important step in our journey to make fediverse bot development more accessible and powerful, introducing several features that our community has been requesting.

The Journey to Better Bot Interactions

In building BotKit, we've always focused on making bots more expressive and interactive. With version 0.2.0, we're taking this to the next level by bringing the social aspects of the fediverse to your bots.

Expressing Your Bot's Personality with Custom Emojis

One of the most requested features has been support. Now your bots can truly express their personality with unique visuals that make their messages stand out.

// Define custom emojis for your bot
const emojis = bot.addCustomEmojis({
  botkit: { 
    file: `${import.meta.dirname}/images/botkit.png`, 
    type: "image/png" 
  },
  fedify: { 
    url: "https://fedify.dev/logo.png", 
    type: "image/png" 
  }
});

// Use these custom emojis in your messages
await session.publish(
  text`BotKit ${customEmoji(emojis.botkit)} is powered by Fedify ${customEmoji(emojis.fedify)}`
);

With this new API, you can:

Engaging Through Reactions

Communication isn't just about posting messages—it's also about responding to others. The new reaction system creates natural interaction points between your bot and its followers:

// React to a message with a standard Unicode emoji
await message.react(emoji`👍`);

// Or use one of your custom emojis as a reaction
await message.react(emojis.botkit);

// Create a responsive bot that acknowledges reactions
bot.onReact = async (session, reaction) => {
  await session.publish(
    text`Thanks for reacting with ${reaction.emoji} to my message, ${reaction.actor}!`,
    { visibility: "direct" }
  );
};

This feature allows your bot to:

Conversations Through Quotes

Discussions often involve referencing what others have said. Our new support enables more cohesive conversation threads:

// Quote another message in your bot's post
await session.publish(
  text`Responding to this interesting point...`,
  { quoteTarget: originalMessage }
);

// Handle when users quote your bot's messages
bot.onQuote = async (session, quoteMessage) => {
  await session.publish(
    text`Thanks for sharing my thoughts, ${quoteMessage.actor}!`,
    { visibility: "direct" }
  );
};

With quote support, your bot can:

Visual Enhancements

Because communication is visual too, we've improved how your bot presents itself:

  • Image attachments now properly display in the web interface
  • Your bot's content looks better and provides a richer experience

Behind the Scenes: Enhanced Activity Propagation

We've also improved how activities propagate through the fediverse:

  • More precise propagation of replies, shares, updates, and deletes
  • Activities are now properly sent to the original message authors

These improvements ensure your bot's interactions are consistent and reliable across different fediverse platforms.

Taking Your First Steps with BotKit 0.2.0

Ready to experience these new features? BotKit 0.2.0 is available on JSR and can be installed with a simple command:

deno add jsr:@fedify/botkit@0.2.0

Since BotKit uses the Temporal API (which is still evolving in JavaScript), remember to enable it in your deno.json:

{
  "imports": {
    "@fedify/botkit": "jsr:@fedify/botkit@0.2.0"
  },
  "unstable": ["temporal"]
}

With these simple steps, you're ready to create or upgrade your fediverse bot with our latest features.

Looking Forward

BotKit 0.2.0 represents our ongoing commitment to making fediverse bot development accessible, powerful, and enjoyable. We believe these new features will help your bots become more engaging and interactive members of the fediverse community.

For complete docs and more examples, visit our docs site.

Thank you to everyone who contributed to this release through feedback, feature requests, and code contributions. The BotKit community continues to grow, and we're excited to see what you'll create!


BotKit is powered by Fedify, a lower-level framework for creating ActivityPub server applications.

1
1
0

Coming soon in 0.2.0: Native post support!

We're excited to share a preview of the upcoming quoting features in BotKit 0.2.0. This update will make it easier for your bots to engage with quoted content across the fediverse.

The quoting feature set includes:

Here's a quick example of how you can use the quote detection:

bot.onQuote = async (session, quote) => {
  // The quote parameter is a Message object representing the post that quoted your bot
  await quote.reply(text`Thanks for quoting my post, ${quote.actor}!`);
  
  // You can access the original quoted message
  const originalPost = quote.quoteTarget;
  console.log(`Original message: ${originalPost?.text}`);
};

And creating quote posts is just as simple:

// Quote in a new post
await session.publish(
  text`I'm quoting this interesting message!`,
  { quoteTarget: someMessage }
);

// Or quote in a reply
await message.reply(
  text`Interesting point! I'm quoting another relevant post here.`,
  { quoteTarget: anotherMessage }
);

Remember that quoting behavior may vary across different implementations—some platforms like Misskey display quotes prominently, while others like Mastodon might implement them differently.

Want to try these features right now? You can install the development version from JSR:

deno add jsr:@fedify/botkit@0.2.0-dev.90+d6ab4bdc

We're looking forward to seeing how you use these quoting capabilities in your bots!

0

친구가 외국 반도체회사에 다니는데 이름만 들으면 다 아는 세계에서 손꼽히는 회사다. 1년 전쯤에, 친구가 자기 팀에서 예전부터 쓰고있는 시뮬레이션 코드가 너무 복잡해서 리팩토링 하고 싶다고 나를 찾아왔다. 한 2, 3000줄 되는 Numpy 코드였다.

나는 시뮬레이션의 의미 자체는 전혀 이해를 못하니(이래서 보안문제도 익스큐즈 할수 있었을 것이다), 그냥 코드의 모양만 보고 이상한 부분을 조금씩 고쳐나갔다. 그... 전형적인 물리학자들의 실험실 코드였다(코드를 못짜는건 이해를 하는데, 거기에 대해 한치의 부끄러움도 느끼지 않는다는 점이 뒷목을 잡게 만든다). Numpy 함수도 제대로 활용을 못해놨길래, 나도 Numpy 잘 못쓰지만 대충 이런 함수가 아마 있겠지... 하고 검색해서 찾아내서 교체하고 이런걸 반복했다.

이것저것 고친 다음에 잘돌아가나 한번 실행을 해봤는데, 이럴수가. 시뮬레이션이 1000배 빨라졌다. 아니 뭐, 한 2배 3배 빨라졌으면 내 솜씨라고 자부할텐데, 1000배 빨라진거는 그냥 원래 코드가 똥통이었다고 해석할수 밖에 없다. 구라안치고 정말 1000배다. 1000배의 성능향상의 보답으로 나는 교촌치킨웨지콤보세트를 현장에서 받아먹었다.

그 이후에 어떤 일이 있었냐. 기존 시뮬레이션 코드로는 하루에 시뮬레이션을 2, 3번정도밖에 돌리지 못했는데, 1000배 빨라지고 나니까 결과가 수십초만에 나오니 하루에 수백번 돌릴수 있게 된것이다(내가 고친 코드가 전부는 아니어서 1000배 향상은 아닌데, 가장 큰 병목이긴 해서 결국 100배 이상이라는 듯). 그때부터 100배 많아진 데이터를 처리하기 위한 인프라가 필요해졌다. 그래서 거기 개발팀이 데이터베이스와 데이터 파이프라인 구축을 시작하게 되었다고 한다. 그 팀에서는 일종의 특이점이 시작된것이다;;

결론: 교촌치킨웨지콤보 세트는 개맛있었다.

28
2
0

We're excited to introduce emoji reactions in the upcoming 0.2.0 release!

With the new Message.react() method, your bot can now react to messages using standard Unicode :

await message.react(emoji`👍`);

support is also included, allowing your bot to react with server-specific emojis:

const emojis = bot.addCustomEmojis({
  // Use a remote image URL:
  yesBlob: {
    url: "https://cdn3.emoji.gg/emojis/68238-yesblob.png",
    mediaType: "image/png",
  },
  // Use a local image file:
  noBlob: {
    file: `${import.meta.dirname}/emojis/no_blob.png`,
    mediaType: "image/webp",
  },
});

await message.react(emojis.yesBlob);

Reactions can be removed using the AuthorizedReaction.unreact() method:

const reaction = await message.react(emoji`❤️`);
await reaction.unreact();

Want to try these features now? You can install the development version from JSR today:

deno add jsr:@fedify/botkit@0.2.0-dev.84+c997c6a6

We're looking forward to seeing how your bots express themselves with this new feature!

Continuing our emoji reaction feature announcement, we're also introducing two new event handlers—Bot.onReact and Bot.onUnreact—that let your bot respond when users react to posts:

// When someone adds an emoji reaction to a post
bot.onReact = async (session, reaction) => {
  // Only respond when the reaction is to your bot's post
  if (reaction.message.actor.id?.href === session.actorId.href) {
    console.log(`${reaction.actor.preferredUsername} reacted with ${reaction.emoji}`);
    
    // You can respond differently based on the emoji
    if (reaction.emoji === "❤️") {
      await session.publish(
        text`Thanks for the love, ${reaction.actor}!`,
        { visibility: "direct" }
      );
    }
  }
};
// When someone removes their emoji reaction
bot.onUnreact = async (session, reaction) => {
  if (reaction.message.actor.id?.href === session.actorId.href) {
    console.log(`${reaction.actor.preferredUsername} removed their ${reaction.emoji} reaction`);
    
    // Optional: respond to reaction removal
    await session.publish(
      text`I noticed you removed your ${reaction.emoji} reaction, ${reaction.actor}.`,
      { visibility: "direct" }
    );
  }
};

These event handlers open up interesting interaction possibilities—your bot can now track popular reactions, respond to specific emoji feedback, or create interactive experiences based on reactions.

Want to try these features now? You can install the development version from JSR today:

deno add jsr:@fedify/botkit@0.2.0-dev.86+cdbb52a2

The full documentation for these features will be available when BotKit 0.2.0 is officially released!

0
4

We're excited to introduce emoji reactions in the upcoming 0.2.0 release!

With the new Message.react() method, your bot can now react to messages using standard Unicode :

await message.react(emoji`👍`);

support is also included, allowing your bot to react with server-specific emojis:

const emojis = bot.addCustomEmojis({
  // Use a remote image URL:
  yesBlob: {
    url: "https://cdn3.emoji.gg/emojis/68238-yesblob.png",
    mediaType: "image/png",
  },
  // Use a local image file:
  noBlob: {
    file: `${import.meta.dirname}/emojis/no_blob.png`,
    mediaType: "image/webp",
  },
});

await message.react(emojis.yesBlob);

Reactions can be removed using the AuthorizedReaction.unreact() method:

const reaction = await message.react(emoji`❤️`);
await reaction.unreact();

Want to try these features now? You can install the development version from JSR today:

deno add jsr:@fedify/botkit@0.2.0-dev.84+c997c6a6

We're looking forward to seeing how your bots express themselves with this new feature!

1

We're excited to announce that 0.2.0 will introduce custom emoji support! This feature allows your bots to express themselves with more personality and engagement.

What's included:

  • Add custom emojis to your bot with Bot.addCustomEmojis()
  • Use emoji in messages with the customEmoji() function
  • Support for both local image files and remote URLs as emoji sources
  • Full integration with BotKit's text formatting system

Simple example:

// Define custom emojis
const emojis = bot.addCustomEmojis({
  botkit: { file: "./botkit.png", type: "image/png" },
  fedify: { url: "https://fedify.dev/logo.png", type: "image/png" }
});

// Use in messages
await session.publish(
  text`Hello world! ${customEmoji(emojis.botkit)}`
);

Want to try it early? You can install the development version from JSR today:

deno add jsr:@fedify/botkit@0.2.0-dev.82+8a0438e6

1

터미널에 대해 궁금한 점이 생겨 자료를 찾다 보니 Windows Console Team에서 연재한 시리즈물을 발견했는데, 그 내용이 참 유익했다.

Windows Command-Line Series:

  1. Backgrounder
  2. The Evolution of the Windows Command-Line
  3. Inside the Windows Console
  4. Introducing the Windows Pseudo Console (ConPTY)
  5. Unicode and UTF-8 Output Text Buffer

콘솔 앱이 터미널과 입출력을 주고 받는 것을 공기처럼 당연하다고 생각했는데, 그 과정에는 커서 이동이나 개행 등과 같은 제어 문자를 렌더링하거나 SIGINT 같은 시그널을 발생시켜주는 처리가 존재했다. 터미널과 콘솔 앱이 서로 분리된 구조가 과거 물리 터미널로부터 비롯된 것도 흥미로웠고 말이다. 사실 이해 못 한 부분이 아직 많아서 다음에 또 읽어볼 생각이다.

6
0
0
1

As someone who has developed several software implementations (Fedify, Hollo, BotKit, and Hackers' Pub), I believe one of the most frustrating features to implement in the is .

The challenges are numerous:

First, there's no standardization. ActivityPub specifications don't define how custom emoji should work, leading to inconsistent implementations across different servers like Mastodon and Misskey.

Rendering is particularly problematic. Emojis must display properly across different contexts (in text, as reactions, in emoji pickers) while maintaining quality at various sizes. Animated emojis add another layer of complexity.

Perhaps most concerning is the poor . Most implementations simply use the emoji code (like :party_blob:) as the alt text, which provides no meaningful information to screen reader users (in particular, non-English speakers) about what the emoji actually depicts or means.

What really dampens my motivation to implement this feature is knowing I'm investing significant effort into something that ultimately creates accessibility barriers. It's disheartening to work hard on a feature that excludes part of the community.

3
6
1

@ayoAyo Ayco :unverified: @hongminhee洪 民憙 (Hong Minhee) It can be so helpful during design! Some people do it first-first. At Astro with our RFC process, minimal "docs" are updated as the feature is developed.

For Astro's new experimental Fonts API, we held not only an open API bash, but an API *docs* bash! After 2 hours looking at the draft docs ("Oh, it works like this? Oh, you expect people to do this? Oh, this is what it takes to explain how to use it?")... some design changes were implemented for sure, and everyone wins!

2

Side quest sneak peek: a browser extension that visualizes (Service Worker) Cache Storage for web sites.

Decided to build this after seeing how difficult it is too see what's stored in Service Worker cache. They can (accidentally) take up quite a lot of storage space.

Repo: github.com/cheeaun/stakataka
Not released yet, under review in Chrome Web Store.

A browser window displaying a website titled "Vite PWA" with a large "PWA" logo. The extension button on the toolbar is clicked showing a popup that says "Stakataka" and a button "Visualize Cache Storage"A screenshot of the Stakataka: Cache Storage Visualizer with a user interface displaying cache data in a treemap format. It shows cache storage usage for various assets, with options to view as a sunburst or table.A screenshot of the Stakataka: Cache Storage Visualizer with options for viewing cache as Treemap, Sunburst, and Table. Sunburst view with cache data is displayed.A screenshot of the Stakataka: Cache Storage Visualizer with a table view selected. The table lists cached items, including a "404.html" file, "apple-touch-icon.png," and "asset-generator/api.html," along with their type and sizes.
1
0
0
0

I've been considering what to add in the next version of BotKit (v0.2.0) and wanted to share my current plans. After reviewing feedback and examining the ecosystem, I've identified three key features that would significantly enhance the framework's capabilities:

  1. Custom emoji support. This would allow bots to use server-defined custom emojis in their messages, making communication more expressive and allowing better integration with instance culture.

  2. Emoji reactions. I plan to implement both sending and receiving emoji reactions to messages. This provides a lightweight interaction model that many users prefer for simple acknowledgments or responses. This would manifest as new event handlers (like Bot.onReaction) and methods (like Message.react()).

  3. Quote posts. The ability to reference other posts with commentary is an important discourse feature in the fediverse. Supporting both sending quotes and detecting when bot posts have been quoted would enable more sophisticated conversational patterns.

These additions should make more capable while maintaining its simple, developer-friendly API. I expect implementation to involve extending the Message class and adding new Text processing capabilities, all while keeping backward compatibility with existing bots. Having built both Hollo and Hackers' Pub, I already have deep familiarity with how various ActivityPub implementations handle these features across the fediverse. I welcome any community feedback on priorities or implementation details before I begin coding.

1
4
0

설정이나 명세를 튜링완전한 언어로 기술하면 안되지 않나, 튜링완전한 언어는 프로그램을 짤때 써야하지 않나란 의견이 있는데, 난 오히려 반대라고 생각한다.

설정/명세를 기술한 코드는 그걸 평가해서 어떤 값을 한번 구하면 끝이고, 임의의 입력에 대해 종료함을 보장할 필요가 없다. 그리고 그 코드의 실행은 서비스 단에서 이루어지는게 아니고, 서비스를 만들고 운영하는 과정에서 이루어지기 때문에 종료되지 않는것에 대해 훨씬 안전하다.

반대로, 실제로 돌아가는 프로그램(말이 좀 이상하지만 excuse부탁드림)이야말로 튜링완전한 언어로 짜면 안된다. 우리가 튜링완전한 언어로 개발하는 이유는 우리가 만드는 프로그램을 기술하는데 필요한 자유도가 얼만큼인지 모르고 작업해야하기 때문에 그렇다. 종료하지않는 엉터리 코드를 짤 가능성을 받아들이면서도, 당장 뭔가 만들긴해야하니까 그런 선택을 하는 것이다.

즉 튜링완전성은 메타프로그래밍을 할때만 허용되는것이 (적어도 이론적으론) 정당하다고 생각한다.



RE: https://hackers.pub/@bgl/019647a2-cd0c-7311-97ce-95b59e5a0696

4

패스키 쓴 이후 나의 해커펍생 달라졌다-

로그인 자체도 안 풀리고 바로 들어오면 된당 며칠 써보니 매우 편하다

1

내가 무슨 쿠버네티스를 쓰고 멀티 AZ 분산을 하고 로드밸런서를 붙이고 수평확장을 하고 매니지드디비를 쓰면 뭐하냐

클라우드프로바이더가 네트워크를 날려먹는데!!!!!!!!!! 아니 그러고도 그걸 감지를 못 해서 내가 티켓을 보낼 때 까지도 모르고 심지어 보낸 직후에도 모르고 몇 번 핑퐁을 해서야 상황파악하고 그 이후로도 해결에 4시간 걸린거 실화냐????????????

1

`contentMap`タームについては、例えば日本語で1万文字程度の記事を7言語くらいに訳し分けるとして、本当にそれらを全て単一のオブジェクトに突っ込みたいのか? という感想がある

1
1

가장 선호하는 JetBrains IDE가 AI 시대에 뒤쳐지고 있어서 안타까웠는데 AI assistant 와 Junie 업데이트로 이제 좀 쓸만해진 것 같다.

여전히 부족한 점이 많기는 하다.
Agent는 느리고, 현재 상태에 대한 가시성이 없어 계속 기다려야할지 중단하고 새로운 세션을 열어야 할지에 대한 판단이 안선다.

prompt를 별도 관리할 수 있게 한 점은 훌륭하나 포맷이나 디렉토리를 유저가 선택할 수 있게 했더라면 더욱 유용했을 것이다. 나는 prompt가 다른 에이전트와 공유 가능하길 원한다.

vscode copilot처럼 Claude로부터 mcp 서버 설정을 불러올 수 있다. 하지만 역시 현재 상태 가시성이 없어 제대로 mcp 서버와 인터랙션이 되고 있는지 확인하기 어렵다.

그럼에도 불구하고 Cursor 나 Copilot에 충분히 대항할만한 업데이트라 생각한다. 앞으로를 응원한다!
https://www.jetbrains.com/ko-kr/junie/

1
1

ThreadsのアカウントがMisskey系からの検索がめちゃくちゃ難しいの、もしかしてアカウントのページ(https://www.threads.net/@アカウント)にtype="application/activity+json"なJSONファイルを用意していないから?

例えばこのアカウントだと
https://c.osumiakari.jp/@oageoというページには<link rel="alternate" href="https://c.osumiakari.jp/users/9go1hrsqih" type="application/activity+json">が入っており、https://c.osumiakari.jp/@oageoを貼り付けるだけで外からでも簡単にアカウントの参照が出来るようになっている(はず)

Mastodonとかでも同様なんだけどThreadsには無さそう

Pleromaにも無いんだけど、Pleromaの場合は表示されている
インスタンスのアドレス/user/ユーザー名でよしなに解決されるから問題ない。しかしThreadsにおいてはhttps://threads.net/ap/users/数字なので、解決されなさそう

0

어제 출시된 o3가 코딩스타일은 별론데 디버깅을 매우 잘한다고 한다.

위 계정은 HVM 만드는 사람의 것인데, 나는 새 모델이 나올때마다 저 사람이 하는 벤치마크를 체크한다. 사실 구체적으로 뭐하는지는 잘 모르는데,

  1. 충분히 어려운 과제로 테스트한다는 점
  2. 진짜로 자기가 할일을 대체할수 있는지 확인할만큼 밀어붙인다는점
  3. 결과를 세세하게 공유한다는 점

에서 참고할만하다.

5

오늘의 오픈소스 기여. Yarn은 참 잘 만든 소트웨어인 것 같다. 엉망진창인 자바스크립트 생태계를 공격적으로 수정해왔다는 점에서 정말 대단한데... 근데 그 생태계가 자정할수록 맞지 않는 부분이 계속 생기는 듯. github.com/toss/yarn-plugin-ca

1

JetBrains IDE도 AI 적용 : 코딩 에이전트, 똑똑한 보조, 무료 티어 포함
------------------------------
- JetBrains는 *AI Assistant와 코딩 에이전트 Junie* 를 포함한 모든 AI 도구를 *하나의 구독 시스템* 에 통합하고 *무료 요금제(AI Free tier)* 를 제공함
- Junie는 *Anthropic Claude, OpenAI 모델 기반의 강력한 AI 코딩 파트너* 로, JetBrains IDE 사용자 모두에게 공개됨
- 새롭게 개선된 AI Assistant는…
------------------------------
https://news.hada.io/topic?id=20377&utm_source=googlechat&utm_medium=bot&utm_campaign=1834

0
2
5
3

reflex-frp 등 FRP 라이브러리들을 쓰면서 배운점은, fire-and-forget이 유용한 패턴이고 많은 코드를 fire-and-forget 방식으로 짤수있음에도 우리는 평소에 그걸 포착하지 못하고 fire-and-remember(but don't use after?) 방식으로 짜고 있다는 것이다. 그리고 더 중요한건, fire-and-forget를 primitive로 삼기에는 fire-and-forget이 안 통하는 순간에 곤란한 점이 많다는 것이다. 그래서 actor 'framework'란 접근에 대해서는 흐린눈을 하고 보게된다.

7

해커즈 퍼브의 favicon 이야기가 나왔을 때 잠깐 생각나는 대로 대충 낙서해 본 것이 있습니다. (말 그대로 대충 낙서입니다. 이대로 쓰자는 뜻은 아닙니다. 너무 진지하게 받아들이지는 마시고, 브레인스토밍 정도로 생각해 주시길...)

  • 퍼브 간판의 일반적인 형상을 가져왔습니다.
  • 마실 것을 파는 장소의 간판 같은 느낌을 유지하면서, 정확히 어떤 음료인지는 의도적으로 알 수 없게 했습니다. ("퍼브"는 맥주를 주력으로 하는 장소라는 인식이 있는 것 같습니다만, 법적·의료적·종교적 여러 가지 이유로 알코올을 음용할 수 없는 사람들이 세상에는 아주 많기 때문에, 일부러 "맥주"의 이미지를 배제했습니다. 해커즈 퍼브는 술 안/못 마시는 사람도 편하게 올 수 있는 장소가 되는 것이, 행동 강령의 취지에도 부합한다는 생각이었습니다.)
  • 간판 부분은 잘 보시면 "퍼브"라는 한글 표기에서 "ㅍ"와 "ㅂ"를 담고 있습니다. 가로대와 간판이 이어지는 부분이 "ㅍ"의 형상이고, 물잔이 "ㅂ"의 형상입니다. 물론 해커즈 퍼브는 한국어 전용 커뮤니티도 아니고 한글 전용 커뮤니티는 더더욱 아닙니다. 한글이 꼭 들어가야 할 이유는 없습니다. 하지만 반대로 한글을 안 쓸 이유도 없지 않은가? 뭔가를 모티브로 쓰긴 써야 하는데 그게 한글일 수도 있는 것 아닌가? 그래서 넣어 봤습니다. 😅
  • "Hacker's Pub"를 구성하는 글자들을 그대로 집어넣는 것을 일부러 피했습니다. 우선, 아이콘은 "Hackers' Pub"이라는 텍스트와 병치될 가능성이 높은데, 그렇다면 "H"나 "P"가 들어 있는 것은 중복이 되고 정보 전달의 낭비가 됩니다. 그리고, favicon 으로 쓰일 가능성이 높은데, 다른 사이트들에도 알파벳을 형상화한 아이콘이 많습니다. 추상적 형상으로서 다른 아이콘들과 겹칠 여지가 적을수록 식별자로서의 기능과 효용이 극대화될 것이라는 생각이었습니다. (물론, 엄밀히 따지면, 이 아이콘도 전체 형상에는 알파벳 "h"의 구조가 숨어 있고, 그것을 의도하긴 했습니다만, 가장 먼저 눈에 들어오는 특징은 아니죠.)
왼쪽의 기둥으로부터 오른쪽으로 뻗은 가로대와, 가로대에 매달린 간판의 형상으로, 간판에는 물잔 모양의 그림
8

洪 民憙 (Hong Minhee) shared the below article:

함수형 언어의 평가와 선택

Ailrun (UTC-5/-4) @ailrun@hackers.pub

함수형 언어(Functional Language)의 핵심

함수형 언어가 점점 많은 매체에 노출되고, 더 많은 언어들이 함수형 언어의 특징을 하나 둘 받아들이고 있다. 함수형 언어, 적어도 그 특징이 점점 대세가 되고 있다는 이야기이다. 하지만, 함수형 언어가 대체 무엇이란 말인가? 무엇인지도 모르는 것이 대세가 된다고 할 수는 없지 않은가?

함수형 언어란 아주 단순히 말해서 함수가 표현식[1]인 언어를 말한다. 다른 말로는 함수가 이기 때문에 다른 함수를 호출해서 함수를 얻어내거나 함수의 인자로 함수를 넘길 수 있는 언어를 말한다. 그렇다면 이 단순화된 핵심만을 포함하는 언어로 함수형 언어의 핵심을 이해할 수 있지 않을까? 이게 바로 람다 대수(Lambda Calculus)의 역할이다.[2]

람다 대수는 딱 세 종류의 표현식만을 가지고 있다.

  1. 변수 (xx, yy, …\ldots)
  2. 매개변수 xx에 인자를 받아 한 표현식 MM(함수의 몸체)을 계산하는 함수 (λx→M\lambda x\to M)
  3. 어떤 표현식 LL의 결과 함수를 인자 NN으로 호출 (L NL\ N)

이후의 설명에서는 MMNN, 그리고 LL이라는 이름을 임의의 표현식을 나타내기 위해 사용할 것이다. 람다 대수가 어떤 것들을 표현할 수 있는가? 앞에서 말했듯이 람다 대수는 함수의 인자와 함수 호출의 결과가 모두 함수인 표현식을 포함한다. 예를 들어 λx→(λy→y)\lambda x \to (\lambda y \to y) 는 매개변수 xx에 인자를 받아 함수 λy→y\lambda y \to y를 되돌려주는 함수이고, λx→(x (λy→y))\lambda x \to (x\ (\lambda y \to y))는 매개변수 xx에 함수인 인자를 받아 그 함수를 (λy→y\lambda y \to y를 인자로 사용하여) 호출하는 함수이다.

람다 대수(Lambda Calculus)의 평가(Evaluation)

이제 문제는

그래서 람다 대수의 표현식이 하는 일이 뭔데?

이다. 위의 표현식에 대한 소개는 산수로 말하자면 x+yx + y와 같이 연산자(++)와 연산항(xxyy)로부터 얻어지는 문법만을 설명하고 있고, 3+53 + 5와 같은 구체적인 표현식을 계산해서 88이라는 결과 값을 내놓는 방식을 설명하고 있지 않다. 이런 표현식으로부터 값을 얻어내는 것을 언어의 "평가 절차"("Evaluation Procedure")라고 한다. 람다 대수의 평가 절차를 설명하는 것은 어렵지 않다. 적어도 표면적으로는 말이다.

  • 함수는 이미 값이다.
  • 함수 λx→M\lambda x \to MNN으로 호출하면 MM에 등장하는 모든 xxNN으로 치환(Substitute)하고 결과 표현식의 평가를 계속한다.

이는 겉으로 보기에는 말이 되는 설명처럼 보인다. 하지만 이 설명을 실제로 해석기(Interpreter)로 구현하려고 시도한다면 이 설명이 사실 여러 세부사항을 무시하고 있다는 점을 깨닫게 될 것이다.

  1. 함수 호출 L NL\ N에서 LL이 (아직) λx→M\lambda x \to M 꼴이 아닐 때는 어떻게 해야하지?
  2. 함수 호출 (λx→M) N(\lambda x \to M)\ N에서 NN을 먼저 평가하는 게 낫지 않나? xxMM에 여러번 등장한다면 NN을 여러번 평가해야 할텐데?

첫번째 문제는 비교적 간단히 해결할 수 있다. LL을 먼저 평가해서 λx→M\lambda x \to M 꼴의 결과 값을 얻어낸 뒤에 호출을 실행하면 되기 때문이다. 반면에 두번째 질문은 좀 더 미묘한 문제를 가지고 있다. 함수 호출의 평가에서 발생하는 이 문제에 구체적인 답을 하기 위해서는 값에 의한 호출(Call-By-Value, CBV)와 이름에 의한 호출(Call-By-Name, CBN)이 무엇인지 이해해야 한다.

값에 의한 호출(Call-By-Value)? 이름에 의한 호출(Call-By-Name)?

앞에서 말한 함수 호출에서부터 발생하는 문제는 사실 함수형 언어에서만 발생하는 문제는 아니다. C와 같은 명령형 언어에서도 함수를 호출할 때 인자를 먼저 평가해야하는지를 결정해야하기 때문이다. 즉 이 문제는 함수를 가지고 있고 함수를 호출해야하는 모든 언어들이 가지고 있는 문제이다.

그렇다면 이 일반적인 문제를 어떻게 해결하는가? 대부분의 언어가 취하는 가장 대표적인 방식은 "값에 의한 호출"("Call-By-Value", "CBV")이라고 한다. 이 함수 호출 평가 절차에서는 함수의 몸체에 인자를 치환하기 전에[3] 인자를 먼저 평가한다. 이 방식을 사용하면 인자를 여러번 평가해야하는 상황을 피할 수 있다.

또 다른 방식은 "이름에 의한 호출"("Call-By-Name", "CBN")이라고 한다. 이 방식에서는 함수의 몸체에 인자를 우선 치환한 후 몸체를 평가한다. 몇몇 언어의 매크로(Macro)와 같은 기능이 이 방식을 사용한다. 얼핏 보기에는 CBN은 장점이 없어보인다. 그러나 함수가 인자를 사용하지 않을 경우는 CBN이 장점을 가진다는 것을 볼 수 있다. 극단적으로 평가가 종료되지 않는 표현식(Non-terminating expression)이 있다면[4] CBV는 종료하지 않고 CBN만이 종료하는 경우가 있음을 다음 예시를 통해 살펴보자. 표현식 (λx→(λy→y)) N(\lambda x \to (\lambda y \to y))\ N이 있다고 할 때, NN이 평가가 종료되지 않는 표현식이라고 하자. 이 경우 CBV를 따른다면 종료하지 않는 NN 평가를 먼저 수행하느라 이 표현식의 값을 얻어낼 수 없지만, CBN을 따른다면 λy→y\lambda y \to y라는 값을 손쉽게 얻어낼 수 있다. 바로 이런 상황 때문에

CBN은 CBV보다 일반적으로 더 많은 표현식들을 평가할 수 있다

고 말한다.

모호한 선택을 피하는 방법

두 방식의 장점을 모두 가질 수는 없을까? 다시 말해서, 어떤 상황에서는 이름에 의한 호출을 사용하고, 어떤 상황에서는 값에 의한 호출을 사용할 수 없을까? 이 질문에 답한 수많은 선구자들 가운데 폴 블레인 레비(Paul Blain Levy)가 내놓은 답인 "값 밀기에 의한 호출"("Call-By-Push-Value", "CBPV")은 함수형 언어의 평가를 기계 수준(Machine level)에서 이해하는데에 있어 강력한 도구를 제공한다. CBPV는 우선 "계산"("Computation")과 "값"("Value")을 구분한다.

  • 계산 MM, NN, LL, …\ldots = 함수 λx→M\lambda x \to M 또는 함수 호출 L VL\ V
  • VV, UU, WW, …\ldots = 변수 xx

잠깐, 앞서서 함수형 언어에서 함수는 값이라고 하지 않았던가? 이는 값 밀기에 의한 호출에서 함수와 함수 호출을 종전과 전혀 다르게 이해하기 때문이다. 함수 λx→M\lambda x \to M는 스택(Stack)에서 값을 빼내어(Pop) xx라는 이름을 붙인 후 MM을 평가하는 것이고, 함수 호출 L VL\ V는 스택에 값 VV를 밀어넣고(Push)[5] LL을 평가하는 것이다. 따라서 함수 λx→M\lambda x \to M는 평가의 결과가 아닌 추가적인 평가가 가능한 표현식이 된다. 이 구분을 간결하게 설명하는 것이 다음의 CBPV 표어이다.

값은 "~인 것"이다. 계산은 "~하는 것"이다.

그렇지만 함수형 언어이기 위해서는 함수를 값으로 취급할 수 있어야 한다고 했지 않은가? 그렇다. 이를 위해 CBPV는

계산을 강제한다면(force\mathbf{force}) 계산 MM를 하는 지연된 계산인 값 thunk(M)\mathbf{thunk}(M)

을 추가로 제공한다. 이 둘 (force(V)\mathbf{force}(V)thunk(M)\mathbf{thunk}(M))을 다음과 같이 문법에 추가할 수 있다.

  • 계산 = λx→M\lambda x \to M 또는 L VL\ V 또는 force(V)\mathbf{force}(V)
  • 값 = xx 또는 thunk(M)\mathbf{thunk}(M)

CBPV를 완성하기 위해 필요한 마지막 조각은 계산을 끝내는 법이다. 현재까지 설명한 λx→M\lambda x \to ML VL\ V 그리고 force(V)\mathbf{force}(V) 는 모두 다음 계산을 이어서 하는 표현식이고, 계산을 끝내는 방법을 제공하지는 않는다. 예를 들어 λx→M\lambda x \to M의 평가는 스택에서 값을 빼내고 계산 MM의 평가를 이어한다. 그렇다면 계산의 끝은 무엇인가? 결과 값을 제공하는 것이다. 이를 위해 return(V)\mathbf{return}(V)를 계산에 추가하고, 이 결과 값을 사용할 수 있도록 M to x→NM\ \mathbf{to}\ x \to N (계산 MM을 평가한 결과 값을 xx라고 할 때 계산 NN을 평가하는 계산) 또한 계산에 추가하면 다음의 완성된 CBPV를 얻는다.

  • 계산 = λx→M\lambda x \to M 또는 L VL\ V 또는 force(V)\mathbf{force}(V) 또는 return(V)\mathbf{return}(V) 또는 M to x→NM\ \mathtt{\mathbf{to}}\ x \to N
  • 값 = xx 또는 thunk(M)\mathbf{thunk}(M)

이제 CBPV를 얻었으니 원래의 목표로 돌아가보자. 어떻게 CBV 호출과 CBN 호출을 CBPV로 설명할 수 있을까?

  • CBV 함수 λx→M\lambda x \to M와 호출 L NL\ N이 있다면, 이를 return(thunk(λx→M))\mathbf{return}{(\mathbf{thunk}(\lambda x \to M))}L to x→N to y→force(x) yL\ \mathbf{to}\ x \to N\ \mathbf{to}\ y \to \mathbf{force}(x)\ y로 표현할 수 있다. 즉, CBPV의 관점에서 CBV의 함수는 지연된 원래 계산 λx→M\lambda x \to M을 값으로 되돌려주는 계산으로 이해할 수 있고, 함수 호출 L NL\ N은 함수 부분 LL을 먼저 평가하고 NN을 평가한 뒤 NN의 계산 결과 yy를 스택에 밀어넣고 지연된 계산인 함수 부분 xx의 계산을 강제하는(force(x)\mathbf{force}(x)) 것으로 이해할 수 있다.
  • CBN 함수 λx→M\lambda x \to M와 호출 L NL\ N이 있다면, 이를 λx→M\lambda x \to M(단, 변수 xx의 모든 사용을 force(x)\mathbf{force}(x)로 치환함)과 L thunk(N)L\ \mathbf{thunk}(N)로 표현할 수 있다. 즉, CBPV의 관점에서 함수 호출은 L NL\ N은 지연된 NN을 스택에 밀어넣은 뒤 LL의 계산을 이어가는 것으로 볼 수 있다. 이 지연된 NN은 이후에 스택에서 빼내어져 어떤 이름 xx가 붙은 뒤, 이 변수가 사용될 때에야 비로소 계산된다.

다소 설명이 복잡할 수 있으나, 단순하게 말해서 CBPV는 CBV에 따른 상세한 평가 순서와 CBN 따른 상세한 평가 순서를 세부적으로 설명할 수 있는 충분한 기능을 모두 갖추고 있으며, 이를 통해 CBV 함수 호출과 CBN 함수 호출을 모두 설명할 수 있다는 이야기이다.

기계 수준(Machine level)에서의 Call-By-Push-Value의 장점

앞에서는 CBPV가 CBV와 CBN를 모두 설명할 수 있음을 다뤘다. 그러나 CBPV는 프로그래머(Programmer)가 직접 사용하기에는 과도하게 자세한 세부사항들을 포함하고 있기에, 프로그래머가 직접 CBPV를 써서 CBV와 CBN의 구분을 조율하기에는 적합하지 않다. 그렇다면 어느 수준에서 CBV와 CBN을 혼합해 사용할 때 도움을 줄 수 있을까? 바로 람다 대수를 기계 수준으로 컴파일(Compile)할 때이다. 이때는 CBPV가 가진 자세한 세부사항의 표현력이 굉장히 유용해진다.

예를 들어 람다 대수를 기계 수준으로 변환할 때 흔히 필요한 것 중 하나인 항수 분석(Arity analysis)에 대해 이야기해보자. 항수 분석은 함수가 하나의 인자를 받은 뒤 실행되어야 하는지, 혹은 두 인자를 모두 받아 실행되어야 하는지 등을 확인하여 이후에 그에 걸맞는 최적화된 기계어(Machine language)를 생성할 수 있게 도와주는 분석 작업이다. 평범한 람다 대수에서는 항수 분석의 결과를 직접적으로 표현하기 어렵다. 예를 들어 람다 대수의 λx→(λy→y)\lambda x \to (\lambda y \to y)의 경우 이 함수가 xxyy를 모두 받아 yy를 되돌려주는 함수인지 (항수가 2인 함수인지), 혹은 xx를 받아 λy→y\lambda y \to y라는 함수를 되돌려주는 함수인지 (항수가 1인 함수인지) 구분할 수 없다. 그러나 이를 CBPV로 변환한 λx→(λy→return(y))\lambda x \to (\lambda y \to \mathtt{return}(y))λx→return(thunk(λy→return(y)))\lambda x \to \mathtt{return}(\mathtt{thunk}(\lambda y \to \mathtt{return}(y)))는 각각이 무엇을 뜻하는지 분명히 이해할 수 있다.

  • λx→(λy→return(y))\lambda x \to (\lambda y \to \mathtt{return}(y))는 두 변수 xxyy를 스택에서 빼낸 뒤 yy의 값을 되돌려주는 함수(항수가 2인 함수)이다.
  • λx→return(thunk(λy→return(y)))\lambda x \to \mathtt{return}(\mathtt{thunk}(\lambda y \to \mathtt{return}(y)))는 변수 xx를 스택에서 빼낸 뒤 지연된 계산 λy→return(y)\lambda y \to \mathtt{return}(y)를 돌려주는 함수(항수가 1인 함수)이다.

이런 장점을 바탕으로 CBPV를 더 발전시킨 "언박싱한 값에 의한 호출"("Call-By-Unboxed-Value")을 GHC 컴파일러의 중간 언어(Intermediate language)로 구현하는 것에 대한 논의가 현재 진행되고 있으며 앞으로 더 많은 함수형 컴파일러들이 관련된 중간 언어를 채용하기 시작할 것으로 보인다.

마치며

이 글에서는 함수형 언어의 핵인 람다 대수를 간단히 설명하고 람다 대수를 평가하는 방법에 대해서 다루어보았다. 특히 그 중 값 밀기에 의한 평가(Call-By-Push-Value, CBPV)가 무엇이며 CBPV가 다른 대표적인 두 방법(CBV, CBN)을 어떻게 표현할 수 있는지, 그리고 CBPV의 장점이 무엇인지에 대해서도 다루어 보았다. 이 글에서 미처 다루지 못한 중요한 주제는 CBPV를 기계에 가까운 언어로 번역해보는 것이다. 여기에서는 글이 너무 복잡해지는 것을 피하기 위해 제했으나, CBPV의 장점에서 살펴봤듯 이는 CBPV에 있어 핵심 주제 중 하나이기 때문에 이후에 다른 글을 통해서라도 이 주제를 소개할 기회를 가지고자 한다. 이 글이 CBPV에 대한 친절한 소개글이었기를 바라며 이만 줄이도록 하겠다.


  1. 결과 (Value)을 가지는 언어 표현을 말한다. 예를 들어 1+11 + 122라는 값을 가지는 표현식이지만 (JavaScript의) let x = 3;나 (Python의) def f(): ...은 그 자체로는 값이 없기 때문에 표현식이 아니다. ↩︎

  2. 다만 실제 역사에서는 람다 대수의 이해와 발견이 함수형 언어의 개발보다 먼저 이루어졌다. 이런 역사적 관점에서는 (이미 많은 수학자들이 이해하고 있던) 람다 대수에 여러 기능을 추가한 것이 바로 함수형 언어라고 볼 수 있다. ↩︎

  3. 프로그래밍 언어(Programming Language)는 실제로는 치환을 사용하지 않고 환경(Environment)을 사용하는 경우가 더 많지만 설명의 편의를 위해 다른 언어들 또한 환경 대신 치환에 기반해 평가한다고 가정하겠다. ↩︎

  4. 앞서 설명한 람다 대수에서는 이를 쉽게 얻을 수 있다. 오메가(Ω\Omega)라고 부르는 표현식인 (λx→x x) (λx→x x)(\lambda x \to x\ x)\ (\lambda x \to x\ x)의 평가는 값에 의한 호출을 따르든 이름에 의한 호출을 따르든 종료되지 않는다. ↩︎

  5. 바로 이 함수 호출을 값 밀기에 기반해 해석하는 데에서 CBPV의 이름이 유래했다. ↩︎

Read more →
13
3
0

여태 모나드 가르칠때 그냥 do notation부터 알려주고 알아서 써보라고했는데 절반정도는 잘 따라왔다. 문법적으로 <-를 넣어야할 위치만 아는 상태에서도 코드를 웬만큼 짰다. 즉, next token prediction은 휴먼에게도 좋은 학습 방법이다.



RE: https://hackers.pub/@xt/01963d1e-e20c-77c5-a395-69c592137fb3

3
0
1

저도 두 가지 쟁점 모두 동의하는 편입니다. 그리고, 별개의 이야기입니다만, $가르칠 때에는 그냥 문법이라고 가르치는 게 학습자의 이해와 응용이 압도적으로 빠르고 좋았습니다.

"이건 여기서부터 뒤로는 다 괄호로 감싸겠다는 뜻이라고 생각하세요."

이러면 한 방에 설명이 끝나고, 필요성이나 편리성에 대해서도 알아서들 납득하는 것이죠. 연산자 우선순위나 좌결합 우결합 등은 그게 되고 나서 얘기하고요. 그러면 "아, 이게 그래서 이렇게 되는 거였군요?" 하면서, 훨씬 쉽게 이해합니다. 이걸 거꾸로 좌결합 우결합 어쩌고부터 가르치려고 하면 다들 꾸벅꾸벅 졸아요... ㅋㅋ ㅠㅠ

(결국 "모나드란 무엇인가"부터 배우면/가르치면 안 된다는 주장과 같은 맥락입니다.)



RE: https://hackers.pub/@bgl/01963c3b-98fa-7432-a62f-0d2dfc0691bf

5

저도 두 가지 쟁점 모두 동의하는 편입니다. 그리고, 별개의 이야기입니다만, $가르칠 때에는 그냥 문법이라고 가르치는 게 학습자의 이해와 응용이 압도적으로 빠르고 좋았습니다.

"이건 여기서부터 뒤로는 다 괄호로 감싸겠다는 뜻이라고 생각하세요."

이러면 한 방에 설명이 끝나고, 필요성이나 편리성에 대해서도 알아서들 납득하는 것이죠. 연산자 우선순위나 좌결합 우결합 등은 그게 되고 나서 얘기하고요. 그러면 "아, 이게 그래서 이렇게 되는 거였군요?" 하면서, 훨씬 쉽게 이해합니다. 이걸 거꾸로 좌결합 우결합 어쩌고부터 가르치려고 하면 다들 꾸벅꾸벅 졸아요... ㅋㅋ ㅠㅠ

(결국 "모나드란 무엇인가"부터 배우면/가르치면 안 된다는 주장과 같은 맥락입니다.)



RE: https://hackers.pub/@bgl/01963c3b-98fa-7432-a62f-0d2dfc0691bf

feedly를 잘 쓰고 있지만 ghost pro의 activityPub 인터그레이션 사용 감각도 괜찮아서, 이걸 충분히 많은 블로그와 웹툰(xkcd도 rss feed를 발행한다) 등이 적용한다면, 연합우주를 좀 더 적극적으로 쓸 수도 있을 것 같다.

2
3

하스켈에서 $가 infix operator가 아니라 문법 요소여야 한다는 얘기에는 동의하는 사람들이 꽤 있다. 근데 1 + $ 2 + 31 + (2 + 3)으로 변환되어야 한다고 하면 다들 싫어한다ㅋㅋ 근데 나는 저것도 좋다고 본다.

3