شعار Functional

Functional

المجتمع
citypaul
functional

Functional programming patterns with immutable data. Use when writing logic, data transformations, or encountering mutation bugs — including any feature request that builds, merges, filters, sorts, prices or otherwise reshapes records, lists, carts, orders or invoices, even when it never mentions immutability; load it alongside tdd for such changes, not instead of it. Covers immutability violations catalog, pure functions, composition, early returns, and options objects. Also use when composing Effect programs or reviewing Effect runtime boundaries in a project that already uses Effect. Do NOT over-apply heavy FP abstractions (monads, fp-ts) unless the project requires them.

نظرة عامة

الناشرcitypaul
المستودع.dotfiles
اسم المهارةfunctional
النجوم
740
التفريعات
96
الملفات المرفقة
3
الروابط
  • تعليمات بصيغة Markdown

    ملف SKILL.md يُحمّله النموذج عند الحاجة، فلا يستهلك توكنات إلا عندما يَرِد طلب ذو صلة فعلًا.

  • تعمل مع أي نموذج لغوي كبير

    مهارات الذكاء الاصطناعي مكتوبة بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا تعمل مع GPT أو Claude أو Gemini أو Grok أو نموذج محلي.

  • الملفات المرفقة: 3

    نصوص برمجية وقوالب ومراجع يمكن للنموذج قراءتها أثناء عمله. الملفات للقراءة فقط ولا تُنفّذ أبدًا.

  • مفتوحة المصدر

    نشرها citypaul على GitHub. اطّلع على المصدر قبل تثبيتها.

التثبيت

ثبّت مهارة الذكاء الاصطناعي Functional في TypingMind لاستخدامها مع أي نموذج لغوي كبير، أو أضفها إلى وكيل ذكاء اصطناعي آخر يقرأ SKILL.md.

1

التثبيت في TypingMind

يُثبّت TypingMind المهارة مباشرةً من مجلدها على GitHub — فيقرأ SKILL.md، ويجمع ملفات الموارد في حزمة، ويحفظ النتيجة محليًا.

  1. افتح التطبيق وانتقل إلى الإضافات → المهارات.
  2. اختر «تثبيت من GitHub».
  3. الصق رابط مجلد المهارة الموضّح أدناه وأكّد التثبيت.
    https://github.com/citypaul/.dotfiles/tree/main/claude/.claude/skills/functional
  4. فعّل المهارة في كل محادثة تريد إتاحتها فيها.
الإضافات → المهارات → إضافة مهارة → من رابط GitHub، ثم الصق رابط المجلد واضغط على «متابعة».
2

التثبيت في وكيل ذكاء اصطناعي آخر

يمكن لأي وكيل ذكاء اصطناعي يقرأ تنسيق Agent Skills استخدام هذه المهارة — انسخ المجلد إلى مجلد المهارات الخاص بذلك الوكيل.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/citypaul/.dotfiles.git /tmp/.dotfiles
mkdir -p .claude/skills
cp -r /tmp/.dotfiles/claude/.claude/skills/functional .claude/skills/functional
أعد تشغيل Claude Code بعد النسخ ليتعرّف على المهارة الجديدة.

استخدمها في TypingMind

فعّل Functional في أي محادثة على TypingMind وسيتولى النموذج الباقي. تتضمن مطالبة النظام اسمها ووصفها، وبمجرد ورود طلب ذي صلة، يُحمّل النموذج التعليمات الكاملة تلقائيًا — فلا تحتاج إلى استدعائها يدويًا، ولا تستهلك أي توكنات حتى تُستخدم فعليًا.

يُحمّل النموذج Functional تلقائيًا بمجرد ورود طلب ذي صلة بها.

تعمل مع أي نموذج ذكاء اصطناعي

مهارات الذكاء الاصطناعي هي تعليمات بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا لا ترتبط Functional بالنموذج الذي كُتبت له. ثبّتها مرة واحدة في TypingMind واستخدمها مع GPT-5 أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو نموذج محلي تشغّله بنفسك — كل ذلك باستخدام مفاتيح API الخاصة بك.

  • تُحمَّل عند الحاجة فقط

    تتضمن مطالبة النظام الاسم والوصف فقط. وتُجلب التعليمات عند أول طلب ذي صلة، لذا لا تترتب أي تكلفة على المهارة غير المستخدمة.

  • بدّل النماذج أثناء المحادثة

    لأن المهارة تعليمات وليست شيفرة، فإن تغيير النموذج لا يعطّلها — فالنموذج التالي يقرأ ملف SKILL.md نفسه.

تعليمات المهارة

هذا هو محتوى SKILL.md الذي يُحمّله النموذج. اقرأه قبل التثبيت — فالمهارة عبارة عن تعليمات سيتبعها نموذجك.

Functional Patterns

Deep-dive resources are in the resources/ directory. Load them on demand:

ResourceLoad when...
immutability-catalog.mdFixing mutation bugs, applying readonly/ReadonlyArray types, or looking up the immutable alternative to an array/object mutation
composition-patterns.mdComposing small functions into pipelines, refactoring monolithic logic, or flattening deeply nested code
effect-runtime.mdWorking in an Effect-based project: runtime boundaries, service requirements, failure handling, interruption, or resource lifetime

Small pure functions are an implementation technique, not a mandate to publish one function per module. Keep related helpers private and colocated when they compose into one coherent responsibility; use codebase-design when choosing the stable caller-facing contract.

Core Principles

  • Immutable domain data by default - build the result and return it; any mutation stays inside the function that created the value and never reaches a value the caller still holds

When the request asks you to change an object in place, the answer is still a new value. Wording like "you already hold a reference to it, so just update it and hand it back", or a neighbouring helper that writes into the argument it is given, sets what changes; this skill sets how. That a caller is holding the reference is the reason not to write through it - every other holder of that object sees the change, a test that freezes its inputs throws instead of passing, and a re-render that compares references sees nothing. Build the result from the inputs ({ ...value, items }, [...xs].sort(...), xs.map(...)), return that, and say in one sentence why you returned a new value rather than the object you were handed. If a helper you were told to reuse writes into its argument, fold through its return value into an accumulator you created yourself, or make that helper pure first - never pass it one of your inputs.

  • Pure functions wherever possible
  • Composition over inheritance
  • Self-documenting code first - keep comments that explain constraints or non-obvious reasons
  • Array methods for transformations - map/filter/reduce whenever the walk visits every element, folds into an accumulator or builds a lookup; a loop earns its place only by exiting early or performing side effects
  • Options objects for parameter groups - keep simple positional APIs simple

Why Immutability Matters

Immutable data is a foundation of functional programming. It makes code predictable (same input → same output, no hidden state changes), debuggable (state does not change underneath a reader), testable (less hidden mutable state), and React-friendly (reconciliation and memoization can rely on reference changes). It also reduces shared-state concurrency hazards, but does not by itself prevent races in I/O or coordination.

typescript
// ❌ WRONG - Mutation creates unpredictable behavior
const user = { name: 'Alice', permissions: ['read'] };
grantPermission(user, 'write'); // Mutates user.permissions internally
console.log(user.permissions); // ['read', 'write'] - SURPRISE! user changed

// ✅ CORRECT - Immutable approach is predictable
const updatedUser = grantPermission(user, 'write'); // Returns new object
console.log(user.permissions); // ['read'] - original unchanged
console.log(updatedUser.permissions); // ['read', 'write'] - new version

When you declare a data type, mark every property readonly and every array ReadonlyArray<T> or readonly T[] — including a type you add to an existing file, and an inline { ... }[] in a parameter position — so the compiler enforces the contract. A mutable property is the exception you justify, not the default. Encapsulated mutable accumulators, caches, and adapter state are acceptable when they do not leak mutation into the domain contract. For common mutations and immutable alternatives, load resources/immutability-catalog.md.


Functional Light

Follow "Functional Light" principles - practical functional patterns without heavy abstractions:

  • DO: pure functions, immutable data, composition, declarative code, array methods, readonly type safety
  • DON'T: category theory, monads, heavy FP libraries (fp-ts, Ramda), over-engineering, functional for its own sake

Why: The goal is maintainable, testable code - not academic purity. If a functional pattern makes code harder to understand, don't use it.

typescript
// ✅ GOOD - Simple, clear, functional
const activeUsers = users.filter(u => u.active);
const userNames = activeUsers.map(u => u.name);

// ❌ OVER-ENGINEERED - Unnecessary abstraction
const compose = <T>(...fns: Array<(arg: T) => T>) => (x: T) =>
  fns.reduceRight((v, f) => f(v), x);
const withoutInactive = compose(
  (users: readonly User[]): readonly User[] => users.filter(u => u.active),
  (users: readonly User[]): readonly User[] => users.filter(u => !u.suspended),
)(users);

Self-Documenting Code and Useful Comments

Code should be clear through naming and structure. Prefer refactoring comments that merely narrate syntax, but keep comments that explain a non-obvious decision or constraint.

Comments worth keeping:

  • JSDoc for public APIs when generating documentation
  • "Why"-comments required by other skills: characterisation test file headers and SUSPICIOUS behavior markers (see the characterisation-tests skill)
  • Constraints the code cannot express (e.g. a workaround pinned to an upstream bug, an ordering requirement imposed by an external system)

❌ WRONG - Comments explaining unclear code

typescript
// Get the user and check if active and has permission
function check(u: any) {
  // Check user exists, then active, then permission
  if (u) {
    if (u.a) {
      if (u.p) return true;
    }
  }
  return false;
}

✅ CORRECT - Self-documenting code

typescript
function canUserAccessResource(user: User | undefined): boolean {
  if (!user) return false;
  if (!user.isActive) return false;
  if (!user.hasPermission) return false;
  return true;
}

// Even better - a single boolean expression
function canUserAccessResource(user: User | undefined): boolean {
  return user !== undefined && user.isActive && user.hasPermission;
}

Check undefined explicitly in the boolean form: optional chaining (user?.isActive && user?.hasPermission) yields boolean | undefined and fails to compile under strict mode.

If a comment only restates what the code does, refactor instead: extract functions with descriptive names, use meaningful variable names, break complex logic into steps, or use type aliases for domain concepts.

✅ Acceptable JSDoc for public APIs

typescript
/**
 * Registers a scenario for runtime switching.
 * @throws {ValidationError} if scenario ID is duplicate
 */
export function registerScenario(definition: ScenaristScenario): void {

Choosing Array Methods and Loops

Prefer map, filter, reduce for transformations. They're declarative (what, not how) and naturally immutable.

✅ CORRECT - map, filter, reduce, and chaining

typescript
const scenarioIds = scenarios.map(s => s.id);
const activeScenarios = scenarios.filter(s => s.active);
const totalActiveMinutes = sessions
  .filter(session => session.active)
  .map(session => session.durationMinutes * session.repetitions)
  .reduce((sum, minutes) => sum + minutes, 0);

When Loops Are Acceptable

Imperative loops are fine when:

  • Early termination is essential (use for...of with break)
  • Performance critical (measure first!)
  • Side effects are necessary (logging, DOM manipulation)

A loop that runs to completion is none of those cases, however clear it reads and whatever it accumulates into. Folding each element into a value you declared just above the loop, grouping by key, building a lookup, or tallying a total is reduce — including a fold that calls a helper, where the accumulator is the helper's return value. A one-to-one rewrite is map; keeping a subset is filter; a lookup keyed by a field is Object.groupBy or a Map built with reduce, not a for...of that sets into one. Choose Array.find(), Array.some(), or Array.every() when those operations express the intent more directly. Keep a loop that already breaks or returns out of its body rather than contorting an early exit into a method chain.


When to Use Options Objects

Use an options object when parameters form a meaningful group, several values share the same type, or optional arguments make ordering unclear. A small, stable function with obvious positional parameters can remain positional.

✅ CORRECT - Options object

typescript
type CreateReportOptions = {
  readonly reportId: string;
  readonly format: 'pdf' | 'csv';
  readonly locale: string;
  readonly timeZone: string;
  readonly includeCharts?: boolean;
  readonly sendEmail?: boolean;
};

function createReport(options: CreateReportOptions): Report {
  const { reportId, format, locale, timeZone, includeCharts = false, sendEmail = true } = options;
  // ...
}

// Call site - crystal clear
createReport({ reportId: 'report_123', format: 'pdf', locale: 'en-GB', timeZone: 'Europe/London', includeCharts: true });

Use positional parameters when the order is obvious, as in add(a, b), or a familiar high-frequency utility would become noisier with an options object. Switch to named options when same-typed or optional arguments make a call ambiguous; parameter count is a signal, not a fixed limit.


Pure Functions

Pure functions have no side effects and always return the same output for the same input:

  1. No side effects - doesn't mutate external state, modify arguments, or perform I/O
  2. Deterministic - same input → same output; no dependency on Date.now(), Math.random(), or globals
  3. Referentially transparent - can replace the call with its return value

Pure functions are testable (no setup/teardown), composable, predictable, cacheable, and parallelizable.

When Impurity Is Necessary

Some functions must be impure (I/O, randomness, side effects). Isolate them:

typescript
// ✅ CORRECT - Isolate impure functions at edges
// Pure core
function calculateTotalWeightGrams(parcels: ReadonlyArray<Parcel>): number {
  return parcels.reduce((sum, parcel) => sum + parcel.weightGrams, 0);
}

// Impure shell (isolated)
async function saveShipment(shipment: Shipment): Promise<void> {
  const totalWeightGrams = calculateTotalWeightGrams(shipment.parcels); // Pure
  await database.save({ ...shipment, totalWeightGrams }); // Impure (I/O)
}

Pattern: Keep concrete I/O at the project's chosen boundaries. Application orchestration may compose effectful capabilities; core domain decisions stay pure. Follow the existing architecture rather than introducing ports and adapters solely to isolate effects.


Early Returns Over Nesting

Treat deep nesting as a readability signal, not a numeric rule. When nested control flow obscures the main path, extract functions or flatten it with guard clauses. For worked examples, load resources/composition-patterns.md.

typescript
// ❌ WRONG - Nested conditions
if (user) {
  if (user.isActive) {
    if (user.hasPermission) {
      // do something
    }
  }
}

// ✅ CORRECT - Early returns (guard clauses)
if (!user) return;
if (!user.isActive) return;
if (!user.hasPermission) return;

// do something

Result Type for Error Handling

Use a Result type when expected failures are part of the caller-facing contract and callers must handle both branches. Preserve an established exception, nullable-value, or framework error convention when it communicates the contract more clearly. Existing business outcome unions can remain values, including refusals: translate them directly at the consumer boundary instead of converting each refusal into an exception or tagged failure and immediately catching it to recover the same outcome.

typescript
type Result<T, E = Error> =
  | { readonly success: true; readonly data: T }
  | { readonly success: false; readonly error: E };

// Usage
function processBatch(batch: Batch): Result<BatchRun> {
  if (batch.itemCount <= 0) {
    return { success: false, error: new Error('Batch must contain an item') };
  }

  const run = executeBatch(batch);
  return { success: true, data: run };
}

// Caller handles both cases explicitly
const result = processBatch(batch);
if (!result.success) return logError(result.error);
console.log(result.data.batchId); // TypeScript knows result.data exists here

Summary Checklist

When writing functional code, verify:

  • Domain data is immutable where that is part of its contract; any mutable state is local and encapsulated
  • Pure functions wherever possible (no side effects)
  • Code is self-documenting; comments explain non-obvious reasons or constraints
  • Array methods or loops are chosen for clarity and control-flow needs
  • Options objects group parameters when they improve the caller-facing contract
  • Composed small functions, not complex monoliths
  • Every property of every data type added is readonly; every array type is ReadonlyArray<T> or readonly T[]
  • Nesting remains readable; guard clauses or extraction clarify deep paths
  • Result types are used when expected failures belong in the return contract

الملفات المرفقة

يقرأ النموذج هذه الملفات عند الحاجة أثناء تحميل المهارة. وهي متاحة للقراءة ولا تُنفّذ أبدًا.

الأسئلة الشائعة

ماذا تفعل مهارة الذكاء الاصطناعي Functional؟

Functional programming patterns with immutable data. Use when writing logic, data transformations, or encountering mutation bugs — including any feature request that builds, merges, filters, sorts, prices or otherwise reshapes records, lists, carts, orders or invoices, even when it never mentions immutability; load it alongside tdd for such changes, not instead of it. Covers immutability violations catalog, pure functions, composition, early returns, and options objects. Also use when composing Effect programs or reviewing Effect runtime boundaries in a project that already uses Effect. Do...

لماذا تستخدم Functional على TypingMind؟

لأنك تثبّتها مرة واحدة وتستخدمها مع أي نموذج. مهارة Functional عبارة عن نص Markdown وليست شيفرة خاصة بمزود بعينه، لذا تعمل المهارة نفسها مع GPT-5 أو Claude أو Gemini أو Grok أو نموذج محلي، ويمكنك تبديل النموذج أثناء المحادثة دون تعطّل المهارة. يعمل TypingMind بمفاتيح API الخاصة بك، فتدفع للمزودين مباشرةً بدلًا من اشتراك لكل مقعد، وتبقى مهاراتك ومحادثاتك في مساحة التخزين الخاصة بك.

كيف أثبّت Functional في TypingMind؟

افتح الإضافات → المهارات → التثبيت من GitHub في TypingMind والصق https://github.com/citypaul/.dotfiles/tree/main/claude/.claude/skills/functional. يقرأ TypingMind ملف SKILL.md الخاص بها، ويجمع ملفاتها ويثبّتها كمهارة يمكنك تفعيلها لكل محادثة على حدة.

ما نماذج الذكاء الاصطناعي التي يمكنها استخدام Functional؟

أي نموذج تربطه في TypingMind. مهارات الذكاء الاصطناعي عبارة عن تعليمات Markdown وليست شيفرة خاصة بمزود بعينه، لذا يمكن لكل من GPT وClaude وGemini وGrok والنماذج المحلية تحميل هذه المهارة عندما يتوافق الطلب معها.

كم نموذج ذكاء اصطناعي يمكنني استخدامه مع Functional؟

أي عدد تريده. ما دام النموذج يدعم المهارات، يمكنك استخدام Functional معه، سواء كان GPT أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو غيرها، وكل ذلك على TypingMind باستخدام مفاتيح API الخاصة بك.

هل مهارة الذكاء الاصطناعي Functional مجانية؟

نشرها citypaul على GitHub. راجع المستودع للاطلاع على شروط الترخيص. لا تدفع إلا لمزود الذكاء الاصطناعي الخاص بك مقابل التوكنات التي تستخدمها.

ما هي مهارات الذكاء الاصطناعي؟

مهارة الذكاء الاصطناعي حزمة تعليمات قابلة لإعادة الاستخدام تعلّم نموذج الذكاء الاصطناعي كيفية تنفيذ مهمة محددة. وتتبع تنسيق Agent Skills المفتوح: ملف SKILL.md يتضمن اسمًا ووصفًا، إلى جانب أي نصوص برمجية أو قوالب أو ملفات مرجعية قد يحتاج إليها النموذج. لا يقرأ النموذج التعليمات إلا عندما يتوافق طلبك مع المهارة، لذا لا تترتب على المهارة المثبتة أي تكلفة حتى تُستخدم.

كيف تختلف مهارات الذكاء الاصطناعي عن الإضافات أو موصلات MCP؟

تمنح الإضافة أو موصل MCP النموذج أدوات جديدة يمكنه استدعاؤها، وهي شيفرة تُنفَّذ في مكان ما وتُرجع نتيجة. أما مهارة الذكاء الاصطناعي فتزوّد النموذج بالمعرفة ومنهجية العمل: كيفية التعامل مع مهمة، والخطوات التي ينبغي اتباعها، وما ينبغي أن تكون عليه المخرجات الجيدة. المهارات عبارة عن نصوص Markdown، لذا لا تحتاج إلى خادم أو مفتاح API أو بيئة تشغيل، وتعمل مع أي نموذج.

عرض الكل

أنشئ مساحة عملك للذكاء الاصطناعي الآن

اشترك في نشرتنا البريدية لتصلك أخبار الميزات الجديدة والهدايا القادمة 👇