You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PureScript中<>运算符工作原理及代码类型匹配错误咨询

Hey there! Let's work through your PureScript questions—this stuff can feel confusing when you're starting out, so let's break it down clearly.

1. Why does flip (\s -> show n <> s) 10 "Ten" throw a type error?

First, let's fix a small implicit detail: your first example works because the lambda is capturing a variable n set to 10 somewhere, but the explicit, reusable version of this function is likely \n s -> show n <> s—a binary function that takes a showable value n and a string s, then returns their concatenation.

Now, let's recall what flip does: its type is flip :: forall a b c. (a -> b -> c) -> b -> a -> c. Plainly put, it takes a binary function f a b and returns a new function that swaps the order of its first two arguments: flip f b a = f a b.

  • When you run flip (\n s -> show n <> s) "Ten" 10, you're feeding the flipped function "Ten" (the original s parameter) as the first argument, and 10 (the original n parameter) as the second. This translates to show 10 <> "Ten", which gives "10Ten"—that checks out.
  • When you try flip (\n s -> show n <> s) 10 "Ten", you're passing 10 as the first argument to the flipped function. But the flipped function expects its first argument to be the original s—a String! 10 is an Int, not a String, so the type checker throws an error because it can't match Int with String (that's the "Could not match type I..." message you're seeing—short for "Int").
2. What's the <> operator's exact behavior?

The <> operator comes from PureScript's Semigroup type class. Its general type is:

(<>) :: forall a. Semigroup a => a -> a -> a

In simple terms, <> is a generic way to combine two values of the same type into another value of that same type. The exact behavior depends on the type's Semigroup instance:

  • For String, <> is string concatenation—so "foo" <> "bar" gives "foobar", which is exactly what's happening in your example (show n returns a String, so show n <> s joins two strings).
  • For List, <> appends two lists: [1,2] <> [3,4] becomes [1,2,3,4].
  • For numeric types like Int, there are multiple Semigroup instances—one using addition (1 <> 2 = 3) and another using multiplication (1 <> 2 = 2), depending on which instance you import.

The hard rule: you can only use <> with two values of the same type, and that type must have a Semigroup instance defined. In your code, since both show n and s are Strings (which have a built-in Semigroup instance), the operator works as concatenation.

内容的提问来源于stack exchange,提问作者Angle.Bracket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:37:58