Article Series

This article series discuss more than 30 different programming languages. Please read overview before you read any of the details.

Playing with Records Related Articles.

Where to Discuss?

Local Group

Preface

Goal: Exploring Fish Shell for string processing.


4: Approach in Solving Unique

A custom example, that you can rewrite.

An Algorithm Case

Why reinvent the wheel?

The same reason as other article.

x:xs Pattern Matching

The same with other article as well.

Exclude Function

Consider array in code below:

set tags \
  "60s" "jazz" "60s" "rock" \
  "70s" "rock" "70s" "pop"

The exclude function is just a filter. Unfortunately, fish does not have diff operator, such as ${tags[@]/$val} in bash.

function exclude
  set -l value $argv[1]
  set -e argv[1]
  set -l tags $argv

  for i in (seq (count $tags) -1 1)
    if [ $tags[$i] = $value ]
      set -e tags[$i]
    end
  end

  string join \n $tags
end

Finally we can call them in main script. and reformat the output using fish.

string join ':' (exclude "rock" $tags)

With the result as below array:

❯ ./11-exclude.sh
60s:jazz:60s:70s:70s:pop

FISH: Exclude Function

The fish script looks tidier than bash.

Recursive Unique Function

With exclude function above, we can build unique function recursively, as below code:

function unique
  if [ (count $argv) -le 1 ]
    echo $argv
  else
    set -l head $argv[1]
    set -e argv[1]
    set -l tail $argv
    
    set -l tags (exclude $head $tail)
    set -l tags (string join \n $tags)
    set -l uniq (unique $tags)

    set -l return $head
    set -a return $uniq
    string join \n $return
  end
end

FISH: The Unique Function

Again, unfortunately, I can’t get rid of exclude function. Because fish does not have array diff operator, or such equivalent.

FISH: The Unique Function

Applying Unique to Simple Array

Now we can apply the method to our unique song challenge.

#!/usr/bin/env fish

set tags \
  "60s" "jazz" "60s" "rock" \
  "70s" "rock" "70s" "pop"

source ./MyHelperUnique.sh
string join ':' (unique $tags)

With the same result as below

FISH: Solving Unique Song

With the result as below array:

❯ ./12-unique-a.sh
60s:jazz:rock:70s:pop

Applying Unique to data Structure

We can also apply the method to our unique song challenge.

#!/usr/bin/env fish
source ./MySongs.sh
source ./MyHelperFlatten.sh
source ./MyHelperUnique.sh

# Extract flatten output to array
set tags (flatten $songs | sort -u)
string join ':' (unique $tags)

With the result as below array:

❯ ./12-unique-b.sh
60s:70s:jazz:pop:rock

FISH: Solving Unique Song


What is Next 🤔?

Consider continue reading [ Ion Shell - Playing with Records - Part One ].