query
On this page

commonPrefix

lib.lists.commonPrefix

Docs pulled from | This Revision | 10 minutes ago


The common prefix of two lists.

Inputs

list1

1. Function argument

list2

2. Function argument

Type

commonPrefix :: [a] -> [a] -> [a]

Examples

lib.lists.commonPrefix usage example

commonPrefix [ 1 2 3 4 5 6 ] [ 1 2 4 8 ]
=> [ 1 2 ]
commonPrefix [ 1 2 3 ] [ 1 2 3 4 5 ]
=> [ 1 2 3 ]
commonPrefix [ 1 2 3 ] [ 4 5 6 ]
=> [ ]

Noogle detected

Implementation

The following is the current implementation of this function.

commonPrefix =
    list1: list2:
    let
      # Zip the lists together into a list of booleans whether each element matches
      matchings = zipListsWith (fst: snd: fst != snd) list1 list2;
      # Find the first index where the elements don't match,
      # which will then also be the length of the common prefix.
      # If all elements match, we fall back to the length of the zipped list,
      # which is the same as the length of the smaller list.
      commonPrefixLength = findFirstIndex id (length matchings) matchings;
    in
    take commonPrefixLength list1;